iterate over array object code example

Example 1: javascript loop through array of objects

var people=[
  {first_name:"john",last_name:"doe"},
  {first_name:"mary",last_name:"beth"}
];
for (let i = 0; i < people.length; i++) { 
  console.log(people[i].first_name);
}

Example 2: loop array of objects

const myArray = [{x:100}, {x:200}, {x:300}];

myArray.forEach((element, index, array) => {
    console.log(element.x); // 100, 200, 300
    console.log(index); // 0, 1, 2
    console.log(array); // same myArray object 3 times
});

Example 3: ho to loop trough an array of objects

yourArray.forEach(function (arrayItem) {
    var x = arrayItem.prop1 + 2;
    console.log(x);
});

Example 4: loop array of objects

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray= myArray.map(element => element.x);
console.log(newArray); // [100, 200, 300]

Example 5: iterate over array of object javascript and access the properties

for (let item of items) {
    console.log(item); // Will display contents of the object inside the array
}