Most modern applications consume external data from other applications and tools through APIs. This data comes in all types of schemas, and it's up to you to deconstruct it until you get what you want to use. Among these schemas is data objects that contain nested arrays. It can be challenging to render this sort of data. This article will teach you how to map over a nested array in a React component.

Using the Map Function

The map function loops over the items of a given array and returns the specified statement or code for each.

For a flat array, the map function works as follows:

        const arr = ['a', 'b', 'c'];

const result1 = arr.map(element => {
  return element;
});

In React, you must wrap the map function with curly brackets and use an arrow function to return a node element for each iteration. The items in the flat array above can be rendered as JSX elements like this:

        const arr = ['a', 'b', 'c']; 

function App () {
return (
<>
{arr.map((item, index) => {
<span key={index}>{a}</span>
})}
</>
)
}

Note that you assign a key to each element the map function returns. This helps React identify items that have been changed or removed. This is important during the reconciliation process.

Mapping Over a Nested Array in a React Component

A nested array is similar to an array that contains another array. For example, the following recipe array contains an object with an array.

        const recipes = [
    {
        id: 716429,
        title: "Pasta with Garlic, Scallions, Cauliflower & Breadcrumbs",
        image: "<https://spoonacular.com/recipeImages/716429-312x231.jpg>",
        dishTypes: [
            "lunch",
            "main course",
            "main dish",
            "dinner"
        ],
        recipe: {
            // recipe data
        }
    }
    
]

For data like this with nested arrays, you should use a map function for each array.

In this example, you would map over the data array as shown below:

        export default function Recipes() {
    return (
        <div>
            {recipes.map((recipe) => {
                return <div key={recipe.id}>
                    <h1>{recipe.title}</h1>
                    <img src={recipe.image} alt="recipe image" />
                    {recipe.dishTypes.map((type, index) => {
                        return <span key={index}>{type}</span>
                    })}
                </div>
            })}
        </div>
    )
}

The Recipes component will render the div element containing the recipe data for each recipe in the recipes array.

Working With Arrays in JavaScript

JavaScript offers a wide variety of array methods that make working with arrays simpler. This article demonstrated how to render data from a nested array using a map array method. Apart from map, there are also methods to help you push data to an array, concatenate two arrays, or even sort an array.