0

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!

1
  • this map is for houses (top level array), you need next maps inside for rooms and devices Commented Apr 8, 2020 at 13:57

2 Answers 2

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>
       )
     }
  })}
Sign up to request clarification or add additional context in comments.

Comments

1

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);
  }
})

1 Comment

Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.