javascript object iterate keys code example

Example 1: javascript iterate object key values

Object.entries(obj).forEach(([key, value]) => {
	console.log(key, value);
});

Example 2: javascript iterate over object keys and values

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 3: javascript loop through object values

var myObj = {foo: "bar", baz: "baz"};
Object.values(myObj).map((val) => {
console.log(val);
})
// "bar" "baz"

Example 4: javascript looping through object

const fruits = {
  apple: 28,
  orange: 17,
  pear: 54,
}

const entries = Object.entries(fruits)
console.log(entries)
// [
//   [apple, 28],
//   [orange, 17],
//   [pear, 54]
// ]

Example 5: javascript looping through object

const fruits = {
  apple: 28,
  orange: 17,
  pear: 54,
}

const keys = Object.keys(fruits)
console.log(keys) // [apple, orange, pear]