Javascript forEach Loop through Array of Objects





Hey guys, in this short article we will discuss how to loop through the array of objects in Javascript. We will discuss several examples using easy to understand examples.

Introduction


In every programming language it is very common that looping through the array, similarly in Javascript also to loop through the array, we will use forEach().

forEach() takes callback function as a parameter. A callback function that accepts up to three arguments.

  • value, which is nothing but the current value
  • index, which is nothing but the index of the current value, index always starts from 0, index is optional
  • array, which is nothing but the entire array, array is optional

forEach() calls the callback function one time for each element in the array.

Loop through the array without arrow function


Consider the following array of numbers, we will loop through the array of numbers using forEach() without using arrow function

const numbers = [1, 2, 3, 4, 5, 6];

numbers.forEach(callback);

function callback(value, index, array) {
    console.log("value "+value, "index "+index);
}

Run the example:

PS C:\workspace\javascript-workspace> node app.js
value 1 index 0
value 2 index 1
value 3 index 2
value 4 index 3
value 5 index 4
value 6 index 5

Loop through the array using arrow function


The below example demonstrates the forEach() with arrow function

const numbers = [1, 2, 3, 4, 5, 6];

numbers.forEach((value, index) => {
    console.log("value "+value, "index "+index);
});

Run the example:

PS C:\workspace\javascript-workspace> node app.js
value 1 index 0
value 2 index 1
value 3 index 2
value 4 index 3
value 5 index 4
value 6 index 5

Loop through the array of objects


The below example demonstrates that how to loop through the array of objects using forEach()

const employees = [
    {
        name: "Bushan", 
        location: "India"
    },
    {
        name: "Bharath",
        location: "India"
    }
];

employees.forEach(employee => {
    console.log(employee);
})

Run the example:

PS C:\workspace\javascript-workspace> node app.js
{ name: 'Bushan', location: 'India' } 
{ name: 'Bharath', location: 'India' }

That’s it for this post, if you like this post, share this with your friends and colleagues or you can share this within your social media platform. Thanks, I will see you in our next post.



Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply