Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to map an array that is inside another in react

I am having trouble with array mappings. There is an array with data I would like to bind to my component. It looks like the following:

export var arrayObjects: IObjects[] = [
{
    name: 'First Object',
    icon: 'bi bi-capsule',
    subMenu: [
        {
            name: 'First Sub Object',
            path: ''
        },
        {
            name: 'Second Sub Object',
            path: ''
        }
    ]
  }
 ]

The array’s type is an interface IObjects which contais name, icon, path and subMenu: IObjects. I need to access the subMenu items in order to create a dynamic menu. Althought, everytime I try to map and call the objects there is no return.

Below you’ll be able to see how the mapping I made goes:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   <ul>
    { arrayNavCadastros.map((item:any, subMenu: any) =>(
       <li className="nav-item">
        <i className={item.icon}></i>
        <a href="">{item.name}</a>
         <ul>
         { subMenu.map((name:any) =>(
           <a href="">{name}</a>
          ))}
         </ul>
        </li>
     )) }
   </ul>

I also tried doing something like <a href="">{item.subMenu.name}</a> but there is also no return.

I’m new to react but I’m used to do these kind of bindings in Angular, which seems way easier since you should only do a loop inside the other subMenu from the arrayObjects… I would appreaciate any help!

Note: when I map the first properties of the arrayObjects (which, from the example, returns ‘First Object’) it works as well as all the titles for the sub menus.

>Solution :

so you have array in subMenu and in each iterate you have object of element
so you need to change this :

 { subMenu.map((name:any) =>(
           <a href="">{name}</a>
          ))}

to this :

 { subMenu.map((sub:any) =>(
           <a href="">{sub.name}</a>
          ))}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading