js 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: js loop through object

const obj = { a: 1, b: 2 };

Object.keys(obj).forEach(key => {
	console.log("key: ", key);
  	console.log("Value: ", obj[key]);
} );

Example 4: javascript loop through array of objects

let arr = [object0, object1, object2];

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

Example 5: js loop over array of objects extract value

var myArr = [{name: 'rich', secondName: 'james'}, {name: 'brian', secondName: 'chris'}];

var mySecondArr = myArr.map(x => x.name);
console.log(mySecondArr);

Example 6: js loop array of objects

// Array of objects
const p = [{
  "p1": "value1",
  "p2": "value2",
  "p3": "value3"
},
{
  "p4": "value4",
  "p5": "value5",
  "p6": "value6"
}];

// Get the objects out of the array
for (let obj of p) {
  // console.log(obj);
  // output: 
  // { p1: 'value1', p2: 'value2', p3: 'value3' }
  // { p4: 'value4', p5: 'value5', p6: 'value6' }
  // Now we can loop the objects in the array by nesting the 'for in' loop inside the 'for of' loop
  for(let key in obj) {
    console.log(key);
    // output:
    // p1
    // p2
    // p3
    // p4
    // p5
    // p6
    // console.log(obj[key]);
    // output
    // value1
    // value2
    // value3
    // value4
    // value5
    // value6
  }
}