Ad

How To Map Over An Object And Render The Arrays Inside The Object Javascript/reactjs?

- 1 answer

const data = {
    "13/11/19": [
    {patientName: "A", room: "room1", user: "k"}, 
    {patientName: "A", room: "room1", user: "k"},
  ], 
    "12/11/19": [
    {patientName: "B", room: "room8", user: "p" }, 
    {patientName: "B", room: "room8", user: "p" },
  ]
}

I have got a data object which has 2 arrays. Inside the data object, I have grouped the array by dates. In the UI I would like to render a row with the date first(13/11/19) then the next rows would be filled with the paitent details (patientName: A) until there is another patient with a different date (12/11/19).

If there is a different date and I would want to add a new row with the new date (12/11/19) then render the patient details(patientName: B) until a different date and so on...

I got started with the following function but I haven't gotton any far from here. How can I render a table with date first and the patients array? thanks in advance.

Object.keys(data).map(obj => 
  console.log(obj) // gives me the date '13/11/19' & '12/11/19'

  console.log(data[obj].map(p => p)) //gives the both patient A & B

 )

UI should be 

Row 1 - 13/11/19 
Row 2 - patientName: "A", room: "room1", user: "k" 
Row 3 - patientName: "A", room: "room1", user: "k" 
Row 4 - 12/11/19 
Row 5 - patientName: "B", room: "room8", user: "p" 
Row 6 - patientName: "B", room: "room8", user: "p
Ad

Answer

Try this:

Object.entries(data).map(([date, patients]) => (
  <div key={date}>
    <h1>{date}</h1>
    <ul>
      {patients.map((patient, i) => (<li key={i}>Patient Name: {patient.patientName}</li>)}
    </ul>
  </div>
))
Ad
source: stackoverflow.com
Ad