React map nested array of objects

In this article, we understand what is Nested array of objects is and how to use react map nested array of objects to iterate array element.

 

React map nested array of objects

 

If you are a developer then often you come across the problem where you have read elements of an array but reading a nested is quite complex compared to a normal array of objects. Let’s first under what is nested array.

 

What is a nested Array?

 

The nested array means an array of an array where the elements of the array are array. See below example array where we have one nested array –

 

Nested Array Example

jsonArray = [{

    SectionName: "Product", items: [
      { "id": 1, "Name": "MacBook" },
      { "id": 2, "Name": "iPhone" },
      { "id": 3, "Name": "iPad" },
      { "id": 4, "Name": "iWatch" }
    ]

  },
  {
    SectionName: "Company", items: [
      { "id": 1, "Name": "Google" },
      { "id": 2, "Name": "FaceBook" },
      { "id": 3, "Name": "IBM" },
      { "id": 4, "Name": "Cisco" }

    ]
  }
];


Here the top-level array is  “jsonArray” and inside this, the array items product and Company have array elements this is called a nested array or array of arrays.

 

React map nested array of objects Example –

 

Now we have to read all the elements of the nested array below is the code example. Copy and paste the below array in the .ts file in your project and import the same in .tsx.

//Nested Array of Object

export const  testData = [{

    SectionName: "Product", items: [
      { "id": 1, "Name": "MacBook" },
      { "id": 2, "Name": "iPhone" },
      { "id": 3, "Name": "iPad" },
      { "id": 4, "Name": "iWatch" }
    ]
  },
  {
    SectionName: "Company", items: [
      { "id": 1, "Name": "Google" },
      { "id": 2, "Name": "FaceBook" },
      { "id": 3, "Name": "IBM" },
      { "id": 4, "Name": "Cisco" }

    ]
  }
];


Now import the JSON array of objects like below.

import { testData } from './jsonData';

 

Iterate nested array using React map method

 

{testJson.map((item) => {
      return (
        <ul>{item.SectionName}
        {item.items.map(child => (
         <li>{child.Name}</li>
        ))}
       </ul>
    );})}

 

Output –

Below is the react map nested array of objects output. Here I have used ul and li to show array items.

React map nested array of objects

 

The map method iterates all the elements of the given array. In this tutorial, we have nested arrays that’s why I have used multiple map methods to read an array of arrays.

 

Conclusion

 

Getting elements from a nested array is a bit complex compared to a normal array but this is how you can use the map method to iterate a nested array of elements using react.

Leave a Reply

Your email address will not be published. Required fields are marked *