Search code examples
reactjsnested-loops

Reactjs Nested Array Mapping


Hi I am trying to map a nested array my json is like this

JSON

[
  {
    "cat_id": 24,
    "cat_name": "Test1",
    "parent_id": 0,
    "sub_cat": [
      {
        "cat_id": 30,
        "cat_name": "SubTest1",
        "parent_id": 24
      }
    ]
  },
  {
    "cat_id": 18,
    "cat_name": "Test2",
    "parent_id": 0,
    "sub_cat": [
      {
        "cat_id": 32,
        "cat_name": "SubTest2",
        "parent_id": 18
      }
    ]
  }
]

I tried this but got error - Parsing error: Unexpected token, expected ","

{

 categories.map((row, key)=>(
 
   <Nav.Link href="#" key={key}>{row.cat_name}</Nav.Link>
        
     {
       row.sub_cat.map((subcat, sub_key) => ( 
         <Nav.Link href="#">{subcat.cat_name}</Nav.Link>
         ))
     }
 
   ) )
}

Any help would be greatly appreciated.


Solution

  • In react we can only have one parent JSX element, you need to wrap the contents of the second map with a parent element like React fragment:

    {categories.map((row, key) => (
        <>
            <Nav.Link href="#" key={key}>
                {row.cat_name}
            </Nav.Link>
            {row.sub_cat.map((subcat, sub_key) => (
                <Nav.Link href="#">{subcat.cat_name}</Nav.Link>
            ))}
        </>
    ))}
    

    Related docs:

    Also your data seems to have natural unique ids, so you had better to use them as key instead of the index.

    {categories.map(row => (
        <>
            <Nav.Link href="#" key={row.cat_id}>
                {row.cat_name}
            </Nav.Link>
            {row.sub_cat.map(subcat => (
                <Nav.Link href="#" key={subcat.cat_id}>{subcat.cat_name}</Nav.Link>
            ))}
        </>
    ))}