javascript loop array of objects code example

Example 1: javascript loop through object example

var person={
 	first_name:"johnny",
  	last_name: "johnson",
	phone:"703-3424-1111"
};
for (var property in person) {
  	console.log(property,":",person[property]);
}

Example 2: javascript loop through array of objects es6

/* new options with IE6: loop through array of objects */

const people = [
  {id: 100, name: 'Vikash'},
  {id: 101, name: 'Sugam'},
  {id: 102, name: 'Ashish'}
];

// using for of
for (let persone of people) {
  console.log(persone.id + ': ' + persone.name);
}

// using forEach(...)
people.forEach(person => {
 console.log(persone.id + ': ' + persone.name);
});
// output of above two methods
// 100: Vikash
// 101: Sugam
// 102: Ashish


// forEach(...) with index
people.forEach((person, index) => {
 console.log(index + ': ' + persone.name);
});
// output of above code in console
// 0: Vikash
// 1: Sugam
// 2: Ashish

Example 3: javascript loop through array of objects

let arr = [object0, object1, object2];

for (let elm of arr) {
  console.log(elm);
}

Example 4: 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 5: 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 6: javascript loop through array of objects

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