This article will discuss how to loop through an array of objects in JavaScript. We will use several methods made available to us by JavaScript.
Use a while loop to iterate over an array in JavaScript
The first method we want to try is a while
loop.
In the example that follows, we have defined an array of objects called people
.
Each object has properties name
, origin
, and alias
. What the while
loop does is display a message about each person in the array.
// define a list of persons
const people = [
{name: "Shang Chi", origin:"China", alias:"Brother Hand"},
{name: "Max Eisenhardt", origin:"Germany", alias:"Magneto"},
{name: "Charles Francis Xavier", origin:"United States", alias:"Professor X"},
{name: "Kamala Khan", origin:"Pakistan", alias:"Ms. Marvel"},
{name: "Wanda Django Maximoff", origin:"Sokovia", alias:"Scarlet Witch"},
{name: "Victor Von Doom", origin:"Latveria", alias:"Doctor Doom"},
{name: "Steven Rogers", origin:"United States", alias:"Captain America"},
{name: "Pietro Django Maximoff", origin:"Sokovia", alias:"Quicksilver"},
{name: "Danielle Moonstar", origin:"United States", alias:"Psyche"}
]
// initialize the index
let idx = 0;
// next variable holds each person object as it is accessed
let person;
// start the while loop
while (idx < people.length) {
// get the current person in the people loop
person = people[idx];
// display the person information
console.log(`${person.name} (aka ${person.alias}) is from ${person.origin}`);
// increment the idx to point to the next person
idx++;
}
Output:
Shang Chi (aka Brother Hand) is from China
Max Eisenhardt (aka Magneto) is from Germany
Charles Francis Xavier (aka Professor X) is from United States
Kamala Khan (aka Ms. Marvel) is from Pakistan
Wanda Django Maximoff (aka Scarlet Witch) is from Sokovia
Victor Von Doom (aka Doctor Doom) is from Latveria
Steven Rogers (aka Captain America) is from United States
Pietro Django Maximoff (aka Quicksilver) is from Sokovia
Danielle Moonstar (aka Psyche) is from United States
In the loop body, we accessed each element of the array using array indexing.
To avoid an infinite loop, the index variable idx
had to be incremented at the end of the loop body, before the next iteration.
The loop ends when idx
equals the number of items in the array.
Using a while
loop gives us access to the power of conditions. We can decide to exit the loop if the built-in while condition fails. We can also make use of break
statements to alter the flow of execution.
Though this method works out all right, we can still make use of a for
loop to eliminate the need to increment the index variable in the loop body.
Using a for loop to iterate over an array of objects in JavaScript
A for
loop can also be used to iterate over items within an array. We are still going to loop over the people
array defined earlier.
However, in this example, we will make use of a for
loop. Using a for
loop eliminates the need to increment the index variable idx
within the loop body, as the incrementation is already defined within the increment expression of the for
statement.
// define a list of persons
const people = [
{name: "Shang Chi", origin:"China", alias:"Brother Hand"},
{name: "Max Eisenhardt", origin:"Germany", alias:"Magneto"},
{name: "Charles Francis Xavier", origin:"United States", alias:"Professor X"},
{name: "Kamala Khan", origin:"Pakistan", alias:"Ms. Marvel"},
{name: "Wanda Django Maximoff", origin:"Sokovia", alias:"Scarlet Witch"},
{name: "Victor Von Doom", origin:"Latveria", alias:"Doctor Doom"},
{name: "Steven Rogers", origin:"United States", alias:"Captain America"},
{name: "Pietro Django Maximoff", origin:"Sokovia", alias:"Quicksilver"},
{name: "Danielle Moonstar", origin:"United States", alias:"Psyche"}
]
// person variable holds each person object as it is accessed
let person;
for (let idx = 0; idx < people.length; idx++) {
// get the current person in the people loop
person = people[idx];
// display the person information
console.log(`${person.name} (aka ${person.alias}) is from ${person.origin}`);
}
Output:
Shang Chi (aka Brother Hand) is from China
Max Eisenhardt (aka Magneto) is from Germany
Charles Francis Xavier (aka Professor X) is from United States
Kamala Khan (aka Ms. Marvel) is from Pakistan
Wanda Django Maximoff (aka Scarlet Witch) is from Sokovia
Victor Von Doom (aka Doctor Doom) is from Latveria
Steven Rogers (aka Captain America) is from United States
Pietro Django Maximoff (aka Quicksilver) is from Sokovia
Danielle Moonstar (aka Psyche) is from United States
The same output is produced when a for
loop is used. Nothing much has changed, except that the increment operation has moved up to the increment expression. This eliminates the problem of forgetting to increment and ending up with an infinite loop.
Using a for
loop to iterate over an array requires an index variable. This is so that we can access each person in the array using array indexing (i.e. people[idx]
accesses the person
at location idx
).
However, if we want to eliminate the need for an index variable (and still simplify our code further), Javascript provides another kind of loop we can make use of; the for of
loop.
Making use of the “for of” loop
The for of
loop iterates over an array and gives access to each object in the array. We define the variable that represents each element in the array as part of the definition of the for of
loop.
In contrast to the for
loop, for of
is simpler and does not require index definition, just the element variable. We will recast our previous example to make use of a for of
loop.
// define a list of persons
const people = [
{name: "Shang Chi", origin:"China", alias:"Brother Hand"},
{name: "Max Eisenhardt", origin:"Germany", alias:"Magneto"},
{name: "Charles Francis Xavier", origin:"United States", alias:"Professor X"},
{name: "Kamala Khan", origin:"Pakistan", alias:"Ms. Marvel"},
{name: "Wanda Django Maximoff", origin:"Sokovia", alias:"Scarlet Witch"},
{name: "Victor Von Doom", origin:"Latveria", alias:"Doctor Doom"},
{name: "Steven Rogers", origin:"United States", alias:"Captain America"},
{name: "Pietro Django Maximoff", origin:"Sokovia", alias:"Quicksilver"},
{name: "Danielle Moonstar", origin:"United States", alias:"Psyche"}
]
for (let person of people) {
// display the person information
console.log(`${person.name} (aka ${person.alias}) is from ${person.origin}`);
}
Output:
Shang Chi (aka Brother Hand) is from China
Max Eisenhardt (aka Magneto) is from Germany
Charles Francis Xavier (aka Professor X) is from United States
Kamala Khan (aka Ms. Marvel) is from Pakistan
Wanda Django Maximoff (aka Scarlet Witch) is from Sokovia
Victor Von Doom (aka Doctor Doom) is from Latveria
Steven Rogers (aka Captain America) is from United States
Pietro Django Maximoff (aka Quicksilver) is from Sokovia
Danielle Moonstar (aka Psyche) is from United States
The difference between using for
and for of
to iterate over arrays is that for
generates indexes that will be used to access the array elements.
While for of
actually goes over each item of the array and assigns them to the person
variable on our behalf so that we can have access to the array object currently referred to in the for of
loop execution.
for of
loops do not give us an option to make use of indices, except we create and manage the index ourselves.
In the following example, we define an index variable idx
and manage the incrementation within the loop.
// define a list of persons
const people = [
{name: "Shang Chi", origin:"China", alias:"Brother Hand"},
{name: "Max Eisenhardt", origin:"Germany", alias:"Magneto"},
{name: "Charles Francis Xavier", origin:"United States", alias:"Professor X"},
{name: "Kamala Khan", origin:"Pakistan", alias:"Ms. Marvel"},
{name: "Wanda Django Maximoff", origin:"Sokovia", alias:"Scarlet Witch"},
{name: "Victor Von Doom", origin:"Latveria", alias:"Doctor Doom"},
{name: "Steven Rogers", origin:"United States", alias:"Captain America"},
{name: "Pietro Django Maximoff", origin:"Sokovia", alias:"Quicksilver"},
{name: "Danielle Moonstar", origin:"United States", alias:"Psyche"}
]
// The index variable we need to manage ourselves
let idx = 0;
for (let person of people) {
// display the person information
console.log(`${person.name} (aka ${person.alias}) is from ${person.origin}`);
// increment the index variable here
idx++;
}
1. Shang Chi (aka Brother Hand) is from China
2. Max Eisenhardt (aka Magneto) is from Germany
3. Charles Francis Xavier (aka Professor X) is from United States
4. Kamala Khan (aka Ms. Marvel) is from Pakistan
5. Wanda Django Maximoff (aka Scarlet Witch) is from Sokovia
6. Victor Von Doom (aka Doctor Doom) is from Latveria
7. Steven Rogers (aka Captain America) is from United States
8. Pietro Django Maximoff (aka Quicksilver) is from Sokovia
9. Danielle Moonstar (aka Psyche) is from United States
We have modified the information produced per object; now we have added a serial number to each object detail.
The reason we have idx + 1
instead of just idx
for the serial number is that since we initialized idx
with 0
, we needed the first object to have a serial number 1
, the second object to have a serial number 2
, and so on.
One could say that manually managing the index variable takes us back to the problem we were trying to avoid with the while
loop.
However, we are not going to have the same problem as with the while
loop; just a different problem. The for of
statement is actually in control of the loop execution; it goes over each object in the people
array and terminates the loop when it has reached the last person.
To demonstrate this, watch what happens when we forget to increment idx
. To do that, we will remove the increment line, while still trying to print the object details with serial numbers.
// define a list of persons
const people = [
{name: "Shang Chi", origin:"China", alias:"Brother Hand"},
{name: "Max Eisenhardt", origin:"Germany", alias:"Magneto"},
{name: "Charles Francis Xavier", origin:"United States", alias:"Professor X"},
{name: "Kamala Khan", origin:"Pakistan", alias:"Ms. Marvel"},
{name: "Wanda Django Maximoff", origin:"Sokovia", alias:"Scarlet Witch"},
{name: "Victor Von Doom", origin:"Latveria", alias:"Doctor Doom"},
{name: "Steven Rogers", origin:"United States", alias:"Captain America"},
{name: "Pietro Django Maximoff", origin:"Sokovia", alias:"Quicksilver"},
{name: "Danielle Moonstar", origin:"United States", alias:"Psyche"}
]
// The index variable we need to manage ourselves
let idx = 0;
for (let person of people) {
// display the person information
console.log(`${person.name} (aka ${person.alias}) is from ${person.origin}`);
}
Output:
1. Shang Chi (aka Brother Hand) is from China
1. Max Eisenhardt (aka Magneto) is from Germany
1. Charles Francis Xavier (aka Professor X) is from United States
1. Kamala Khan (aka Ms. Marvel) is from Pakistan
1. Wanda Django Maximoff (aka Scarlet Witch) is from Sokovia
1. Victor Von Doom (aka Doctor Doom) is from Latveria
1. Steven Rogers (aka Captain America) is from United States
1. Pietro Django Maximoff (aka Quicksilver) is from Sokovia
1. Danielle Moonstar (aka Psyche) is from United States
Notice that the loop terminates (unlike what we would face if we forgot the increment when using a while
loop).
However, we have a different kind of bug; the serial numbers are not correct! Would it not be nice if we could have a bit of both worlds – access to array item and index, and control in the hands of Javascript? The array.forEach()
method gives us such a feature.
Use the forEach method to iterate through an array
When making use of while
and for
loops, we also defined an item variable (a variable to hold each array item, or object as it was accessed in the loop). The variable in question, person
, was defined before the loop started, and was updated each time we retrieved an object from the array.
With Javascript’s array.forEach()
method, however, the person
variable is defined as part of the loop’s callback function parameter. We can see how this simplifies our code further in the next example.
// define a list of persons
const people = [
{name: "Shang Chi", origin:"China", alias:"Brother Hand"},
{name: "Max Eisenhardt", origin:"Germany", alias:"Magneto"},
{name: "Charles Francis Xavier", origin:"United States", alias:"Professor X"},
{name: "Kamala Khan", origin:"Pakistan", alias:"Ms. Marvel"},
{name: "Wanda Django Maximoff", origin:"Sokovia", alias:"Scarlet Witch"},
{name: "Victor Von Doom", origin:"Latveria", alias:"Doctor Doom"},
{name: "Steven Rogers", origin:"United States", alias:"Captain America"},
{name: "Pietro Django Maximoff", origin:"Sokovia", alias:"Quicksilver"},
{name: "Danielle Moonstar", origin:"United States", alias:"Psyche"}
]
people.forEach(person => {
// display the person information
console.log(`${person.name} (aka ${person.alias}) is from ${person.origin}`);
});
Output:
Shang Chi (aka Brother Hand) is from China
Max Eisenhardt (aka Magneto) is from Germany
Charles Francis Xavier (aka Professor X) is from United States
Kamala Khan (aka Ms. Marvel) is from Pakistan
Wanda Django Maximoff (aka Scarlet Witch) is from Sokovia
Victor Von Doom (aka Doctor Doom) is from Latveria
Steven Rogers (aka Captain America) is from United States
Pietro Django Maximoff (aka Quicksilver) is from Sokovia
Danielle Moonstar (aka Psyche) is from United States
This is were forEach()
method and for of
loops are similar; the item variable person
is defined as part of the loop definition. The difference with for of
.
However, is that we also have access to an index. forEach()
allows us to specify an optional index variable as part of the parameters of the callback function.
We can use the index information to modify each line of output for our array objects.
The next code example, and output, illustrate this.
// define a list of persons
const people = [
{name: "Shang Chi", origin:"China", alias:"Brother Hand"},
{name: "Max Eisenhardt", origin:"Germany", alias:"Magneto"},
{name: "Charles Francis Xavier", origin:"United States", alias:"Professor X"},
{name: "Kamala Khan", origin:"Pakistan", alias:"Ms. Marvel"},
{name: "Wanda Django Maximoff", origin:"Sokovia", alias:"Scarlet Witch"},
{name: "Victor Von Doom", origin:"Latveria", alias:"Doctor Doom"},
{name: "Steven Rogers", origin:"United States", alias:"Captain America"},
{name: "Pietro Django Maximoff", origin:"Sokovia", alias:"Quicksilver"},
{name: "Danielle Moonstar", origin:"United States", alias:"Psyche"}
]
people.forEach((person, idx) => {
// display the person information, with a serial number for each person
console.log(`${idx + 1}. ${person.name} (aka ${person.alias}) is from ${person.origin}`);
});
Output:
1. Shang Chi (aka Brother Hand) is from China
2. Max Eisenhardt (aka Magneto) is from Germany
3. Charles Francis Xavier (aka Professor X) is from United States
4. Kamala Khan (aka Ms. Marvel) is from Pakistan
5. Wanda Django Maximoff (aka Scarlet Witch) is from Sokovia
6. Victor Von Doom (aka Doctor Doom) is from Latveria
7. Steven Rogers (aka Captain America) is from United States
8. Pietro Django Maximoff (aka Quicksilver) is from Sokovia
9. Danielle Moonstar (aka Psyche) is from United States
Now each line of our output displays a serial number, along with the object’s information.
Since indexes are zero-based, We had to add 1
so that the first object has a serial number 1
instead of 0
. Just like with for
loops, the index variable is automatically managed, so we do not need to worry about forgetting to increment the index.
forEach
loops have a limitation that is inherent in their use of callback functions – we cannot make use of break
to break out of a forEach
loop. We just have to completely iterate through all the array objects.
Conclusion
In this tutorial, we have discussed some ways we can loop through an array of objects in javascript. Thanks for reading the tutorial up to this point. If you liked this tutorial, you can also check out others on our website.