Get data of array containing array in reactjs

Viewed 98

I want to get the data from an array inside an array to create a condition for my CSS class on the element. So far I am able to make it work for one array but the data is having another array inside it.

So want to create a condition when we have data inside the second array.

Following is the sample : https://stackblitz.com/edit/react-v9iknk

This is the function

getData = (menu) => {

     return <li className={menu.children !== undefined && menu.children.length > 0 ? 'nav-item ddfull subnav' : 'nav-item'}>
            <a href={menu.link} className="nav-link">{menu.name}</a>
            {(menu.children !== undefined && menu.children.length > 0) &&
                <div className="ddmenu">
                    <ul>
                        {
                            menu.children.map(data => {
                                return this.getData(data);
                            })
                        }

                    </ul>
                </div>
            }
            </li>

    }

The problem is with this line when I change it to :

 return <li className={menu.children.children !== undefined && menu.children.children.length > 0 ? 'nav-item ddfull subnav' : 'nav-item'}>

Below is the JSON format :

{ "name": "level1.3", "link": "#", 
      "children": [
        { "name": "level1.3.1", "link": "#", 
          "children": [
            { 
              "name": "level1.3.1.1", "link": "#" }
            ] 
        }, 
        { "name": "level1.3.1.2", "link": "#", 
      "children": [
        { "name": "level1.3.1.2", "link": "#" }
        ] }
        ] 
      }

Note: I tried with the following because it is an array inside array not an object but getting undefined error

menu.children[0].children
1 Answers

use both the conditions menu.children !== undefined and menu.children[0].children !== undefined to check for the inner data:

 <li className={(menu.children!== undefined && menu.children.length > 0  &&menu.children[0].children !== undefined && menu.children[0].children.length > 0)? 'nav-item ddfull subnav' : 'nav-item'}>

you can also use get method from lodash

Related