foreach object javascript examples

Example 1: 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 2: 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