Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to map a nested object without wasting too much if your time.
The question is published on by Tutorial Guruji team.
The question is published on by Tutorial Guruji team.
I have to populate the li element with data stored as a JSON object. With “title” it works simple. But it’s not when talking about name’s values. How can I map the subMenu object to get the name?
<ul> {data.map(({ title, subMenu }) => ( <li className="mobileMenu-body-nav-item"> <button className="mobileMenu-body-nav-item-btn"> *** here I have to put name *** </button> </li> ))} </ul>
JSON object
[ { "title": "Breeds", "subMenu": [ { "id": 1, "name": "Dog Breeds" }, { "id": 2, "name": "Cat Breeds" } ] }, { "title": "About Pet Adoption", "subMenu": [ { "id": 3, "name": "About Dog Adoption" }, { "id": 4, "name": "About Cat Adoption" } ] } ]
Answer
You can just call map
again, like this:
<ul> {data.map(({ title, subMenu }) => ( <li className="mobileMenu-body-nav-item"> <button className="mobileMenu-body-nav-item-btn"> {subMenu.map(({ name }) => (<span>{name}</span>))} </button> </li> ))} </ul>
Change the <span>
tag to match however you want this content to be rendered.
Also, if this is React, don’t forget to set the key
prop appropriately when using map
:
<ul> {data.map(({ title, subMenu }) => ( <li key={title} className="mobileMenu-body-nav-item"> <button className="mobileMenu-body-nav-item-btn"> {subMenu.map(({ name }) => (<div key={name}>{name}</div>))} </button> </li> ))} </ul>
We are here to answer your question about How to map a nested object - If you find the proper solution, please don't forgot to share this with your team members.