foreach in object js code example

Example 1: foreach object javascript

const students = {
  adam: {age: 20},
  kevin: {age: 22},
};

Object.entries(students).forEach(student => {
  // key: student[0]
  // value: student[1]
  console.log(`Student: ${student[0]} is ${student[1].age} years old`);
});
/* Output:
Student: adam is 20 years old
Student: kevin is 22 years old
*/

Example 2: javascript loop through object

for (var property in object) {
  if (object.hasOwnProperty(property)) {
    // Do things here
  }
}

Example 3: javascript foreach object

const list = {
  key: "value",
  name: "lauren",
  email: "[email protected]",
  age: 30
};

// Object.keys returns an array of the keys
// for the object passed in as an argument.

Object.keys(list).forEach(val => {
  let key = val;
  let value = list[val];
  console.log(`${key} : ${value}`);
});

// Returns:
// "key : value"
// "name : lauren";
// "email : [email protected]"
// "age : 30"

Example 4: object foreach

const obj = {
  name: 'Jean-Luc Picard',
  rank: 'Captain'
};

// Prints "name Jean-Luc Picard" followed by "rank Captain"
Object.keys(obj).forEach(key => {
  console.log(key, obj[key]);
});

Example 5: foreach object js

const object1 = {
  a: 'somestring',
  b: 42
};
for (let [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}
// expected output:
// "a: somestring"
// "b: 42"
// order is not guaranteed

Example 6: for each element in object

var obj = {
  first: "John",
  last: "Doe"
};

//
//	Visit non-inherited enumerable keys
//
Object.keys(obj).forEach(function(key) {

  console.log(key, obj[key]);

});