Sometimes we need to loop through arrays to render components, content, or simply retrieve object data in React.

Let’s explore various ways to loop through an array of objects in React.

1. map()

export default function App() {
  const data = [
    { firstName: "George", lastName: "Smith", job: "writer", salary: 50000 },
    { firstName: "Michael", lastName: "Handler", job: "DJ", salary: 150000 },
    { firstName: "Larry", lastName: "David", job: "writer", salary: 250000 },
    { firstName: "Mindy", lastName: "Smith", job: "cook", salary: 120000 }
  ];
  return (
    <div className="App">
      {data.map((person) => (
        <div className="card">
          <p>{person.firstName}</p>
          <p>{person.lastName}</p>
          <p>{person.job}</p>
          <p>{person.salary}</p>
        </div>
      ))}
    </div>
  );
}

Reasons to use map():

  1. The least amount of code
  2. Render components within JSX

2. forEach()

export default function App() {
  const data = [
    { firstName: "George", lastName: "Smith", job: "writer", salary: 50000 },
    { firstName: "Michael", lastName: "Handler", job: "DJ", salary: 150000 },
    { firstName: "Larry", lastName: "David", job: "writer", salary: 250000 },
    { firstName: "Mindy", lastName: "Smith", job: "cook", salary: 120000 }
  ];
  return (
    <div className="App">
      {data.map((person) => (
        <div className="card">
          <p>{person.firstName}</p>
          <p>{person.lastName}</p>
          <p>{person.job}</p>
          <p>{person.salary}</p>
        </div>
      ))}
    </div>
  );
}

Reasons to use forEach():

  1. It’s clear what function does.
  2. To run a side effect.

3. for loop

const elementsArray = [];
  for (let i = 0; i < data.length; i++) {
    elementsArray.push(
      <div className="card">
        <p>{data[i].firstName}</p>
        <p>{data[i].lastName}</p>
        <p>{data[i].job}</p>
        <p>{data[i].salary}</p>
      </div>
    );

Reasons to use for loop:

  1. Familiar syntax.
  2. Run a side effect for each object

4. filter() to conditionally loop through an array of objects

data.filter((object) => object.salary > 120000)
  1. To conditionally return some objects
  2. Can be embedded in JSX

We’ll also explain how to use object data to render components and elements in React.

So you’ll learn how to render components for each object in the array.

The map() method

The most common method for looping through an array of objects in React. It takes one argument – a callback function to specify ‘what to do with’ every item in the array. It is useful if you want to modify each item. map() returns a new array with modified items.

Let’s look at an example:

export default function App() {
  const data = [
    { firstName: "George", lastName: "Smith", job: "writer", salary: 50000 },
    { firstName: "Michael", lastName: "Handler", job: "DJ", salary: 150000 },
    { firstName: "Larry", lastName: "David", job: "writer", salary: 250000 },
    { firstName: "Mindy", lastName: "Smith", job: "cook", salary: 120000 }
  ];
  return (
    <div className="App">
      {data.map((person) => (
        <div className="card">
          <p>{person.firstName}</p>
          <p>{person.lastName}</p>
          <p>{person.job}</p>
          <p>{person.salary}</p>
        </div>
      ))}
    </div>
  );
}

data variable holds an array of objects. We can call map() method on the array and pass it a callback function that specifies ‘how to modify’ every object in the array. Argument to the callback function itself (in this case, person) represents each object in the array.

In this example, callback function renders paragraph elements (<p>) and uses person.firstName, person.lastName, and other object values as paragraph contents.

For every object in the array, map() will create a new <div> with a className ‘card’, and use property values to render paragraphs.

A great advantage of using map() method (over forEach() method) is that you can loop through an array of objects within JSX, as long as the expression is wrapped with curly braces.

To recap: map() will go through every item in the array, run callback function on it, and return new array with modified array items.

Often times we use map() to return array of React components or elements, like in the example above.

The forEach() method

You can also use this method, but it takes more lines of code. This is because forEach() performs a side effect on every object in the array.

Still, forEach() is useful if you want to ‘do’ something for every object in the array. For example, log something to the console for every iteration.

forEach() also takes a callback function argument. It executes that callback function for every object in the array.

Unlike map(), forEach() does not return anything. Only performs side effects on objects.

To create a new array from an array of objects, you’ll have to manually store each item in a new array. Let’s look at an example:

export default function App() {
  const data = [
    { firstName: "George", lastName: "Smith", job: "writer", salary: 50000 },
    { firstName: "Michael", lastName: "Handler", job: "DJ", salary: 150000 },
    { firstName: "Larry", lastName: "David", job: "writer", salary: 250000 },
    { firstName: "Mindy", lastName: "Smith", job: "cook", salary: 120000 }
  ];
  const elementsArray = [];
  data.forEach((person) => {
    elementsArray.push(
      <div className="card">
        <p>{person.firstName}</p>
        <p>{person.lastName}</p>
        <p>{person.job}</p>
        <p>{person.salary}</p>
      </div>
    );
  });
  return <div className="App">{elementsArray}</div>;
}

First, we have a data variable to store an array of objects.

We create elementsArray to store elements created for every object in the original array.

We call the forEach() method on data. We call push() to save React elements in the new elementsArray.

Finally, we reference the elementsArray array within JSX, which will display all elements in the array.

Use for to loop through an array of objects in React

Before ES6, most of us used for to loop through array.

To write a for loop, we need to do three things:

  1. Initialize the index (Often named i, and set to 0).
  2. Write the condition. for loop will continue as long as this condition is met. Let’s say that i should be lower than the number of objects in the array.
  3. Expression to execute after every iteration (increment i variable by 1).

So the for loop starts with first object (at index 0). After this iteration, we increase i by 1, so it goes to the second objecet (at index 0). And it continues until i is equal to the length of array.

Let’s skip to example:

const elementsArray = [];
  for (let i = 0; i < data.length; i++) {
    elementsArray.push(
      <div className="card">
        <p>{data[i].firstName}</p>
        <p>{data[i].lastName}</p>
        <p>{data[i].job}</p>
        <p>{data[i].salary}</p>
      </div>
    );

During every iteration, you take data from the object at i position in the data array.

On first iteration, this will be 0. It will continue looping until we reach data[4], fifth element in the array. But the array is only 4 elements wrong. So the condition (i should be less than length of the array) will fail, and for loop will stop.

Note that you need to define the elementsArray outside of for loop.

Advantage of the for loop is that it’s more customizable than these methods. For example, you can increase i by 2 and skip some objects.

Loop through an array of objects conditionally

As a final example, let’s explain how to loop through an array of objects and only keep objects that satisfy a condition. Let’s stick with data from previous examples:

const data = [
    { firstName: "George", lastName: "Mccarthy", job: "writer", salary: 50000 },
    { firstName: "Michael", lastName: "Handler", job: "DJ", salary: 150000 },
    { firstName: "Larry", lastName: "David", job: "writer", salary: 250000 },
    { firstName: "Mindy", lastName: "Smith", job: "cook", salary: 120000 }
  ];

The filter() method in JavaScript takes one argument – a callback function that checks if items in the array (in this case, objects) meet that criteria. It returns an array of objects that met the condition.

Let’s look at an example:

data.filter((object) => object.salary > 120000)

Callback function in this filter() method will return objects where the value of salary property is higher than 120000, and discard other objects.

It’s possible to chain the map() method on the result of filter() method. This way, you can loop through the array of filtered objects.

data.filter((object) => object.salary > 120000).map(person => person.firstName)

In this case, map() will return a new array, comprised of firstName values of objects that met salary criteria.