Solution 1 :

You need to do a second and third .map inside our first map in order to return both rooms:

{props.house.map(house => {

     return (
         <React.Fragment>
             <Card>
                 <Card.Body>
                     {
                         house.rooms.map((room) => (
                             room.map((device) => (
                                <Card.Title>{device.device_name}</Card.Title>
                             )
                         )
                      }
                 </Card.Body>
              </Card>
          </React.Fragment>
       )
     }
  })}

Solution 2 :

You have 2 levels in your array, when you do props.house.map, you only get the first level object: dwelling. If you want to list all the rooms of a dwelling, then you need to make a second map like this:

props.house.map(dwelling => {
  dwelling.map(room => {
    console.log(room.devices[0].device_name);
  }
})

Problem :

When I use map() to return the names of devices in my database, it only returns the first name.
I am not very confident with JavaScript so this may be a simple issue.

Here’s my database:

[{
   "dwelling_id": 1,
   "rooms": [{
       "room_id": 1,
       "room_name": "Living Room",
       "devices": [{
          "id": 1,
          "device_name": "Google Home",
        }]
      },
      {
        "room_id": 2,
        "room_name": "BedRoom",
        "devices": [{
           "id": 2,
           "device_name": "Smart Bulb 1",
        }]
       }...

Here’s the code to return both Google Home and Smart Bulb in separate Bootstrap Cards:

{props.house.map(house => {
     return (
        <React.Fragment>
           <Card>
              <Card.Body>
                 <Card.Title>
                   {house.rooms[0].devices[0].device_name}
                 </Card.Title>
              </Card.Body>
           </Card>
        </React.Fragment>
     )}
})}

If I do this:

// If I change this...
{house.rooms[0].devices[0].device_name} 
// to...
{house.rooms[1].devices[0].device_name}

My code only returns just Smart Bulb.
Note that I want to return both Google Home and Smart Bulb in two separate Cards.
Any help would be greatly appreciated, thank you!

Comments

Comment posted by xadm

this

Comment posted by ajnabz

Thank you very much!

By