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
- Loop through an array of objects using for of
- Loop through an array of objects using Object.entries()
- Loop through an array of objects using for in
Loop through an array of objects using forEach
Example:-
Loop through an array of objects and print each of them on the console.
Code:-
Frequently Asked:
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:
- Loop through an array in javascript (6 ways)
- Javascript: Insert an item to array at specific index
- Javascript: Check if an array is empty
- Javascript: Convert array to string (4 ways)
I hope this article helped you to loop through an array of objects in javascript. Good Luck !!!