Javascript: loop through an array of objects

While working in javascript arrays, we often need to loop through an array of objects to process each of them. This article will see different ways to loop through an array of objects, along with example illustrations.

Table of Contents:

Loop through an array of objects using forEach

Example:-

Loop through an array of objects and print each of them on the console.

Code:-

var myArray = [
  { voterName: 'Paul', eligibility: 'Yes' },
  { voterName: 'Eva', eligibility: 'No'},
  { voterName: 'Veronica', eligibility: 'Yes' }
];
myArray.forEach(object => console.log(object));

Output:-

{ voterName: 'Paul', eligibility: 'Yes' }
{ voterName: 'Eva', eligibility: 'No' }
{ voterName: 'Veronica', eligibility: 'Yes' }

Loop through an array of objects using for of

Example:-

Loop through an array of objects and print each of them on the console.

Code:-

var myArray = [
  { voterName: 'Paul', eligibility: 'Yes' },
  { voterName: 'Eva', eligibility: 'No'},
  { voterName: 'Veronica', eligibility: 'Yes' }
];
for (var object of myArray) {
  console.log(object)
}

Output:-

{ voterName: 'Paul', eligibility: 'Yes' }
{ voterName: 'Eva', eligibility: 'No' }
{ voterName: 'Veronica', eligibility: 'Yes' }

Loop through an array of objects using Object.entries()

Javascript’s Object.entries() returns an array of given object’s own enumerated key-value pairs.

Example:-

Loop through an array of objects and print each of them on the console.

Code:-

var myArray = [
  { voterName: 'Paul', eligibility: 'Yes' },
  { voterName: 'Eva', eligibility: 'No'},
  { voterName: 'Veronica', eligibility: 'Yes' }
];
for (const [_, object] of Object.entries(myArray))
{
  console.log(object);
}

Output:-

{ voterName: 'Paul', eligibility: 'Yes' }
{ voterName: 'Eva', eligibility: 'No' }
{ voterName: 'Veronica', eligibility: 'Yes' }

Loop through an array of objects using for in

Example:-

Loop through an array of objects and print each of them on the console.

Code:-

var myArray = [
  { voterName: 'Paul', eligibility: 'Yes' },
  { voterName: 'Eva', eligibility: 'No'},
  { voterName: 'Veronica', eligibility: 'Yes' }
];
for (i = 0; i < myArray.length; i++) 
{
    for (var object in myArray[i]) 
    {
    console.log("object" + [i]+"->"+object + ":" + myArray[i][object] );
    }
}

Output:-

object0->voterName:Paul
object0->eligibility:Yes
object1->voterName:Eva
object1->eligibility:No
object2->voterName:Veronica
object2->eligibility:Yes

Read More:

I hope this article helped you to loop through an array of objects in javascript. Good Luck !!!

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top