Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to loop through an object's properties

Short answer

Object.entries() returns name-and-value pairs that are convenient to walk with for...of:

const user = { name: 'Anna', age: 25 };
 
for (const [key, value] of Object.entries(user)) {
  console.log(key + ': ' + value);
}

Output:

name: Anna
age: 25

Names only or values only

Object.keys() and Object.values() do that:

const user = { name: 'Anna', age: 25 };
 
console.log(Object.keys(user).join(', '));
console.log(Object.values(user).join(', '));

Output:

name, age
Anna, 25

The for...in loop

for...in walks over the keys of an object:

const prices = { tea: 3, cake: 5 };
 
for (const key in prices) {
  console.log(key, prices[key]);
}

Output:

tea 3
cake 5

Common mistake

for...of does not work with an ordinary object directly, because an object is not iterable. Use Object.entries():

try {
  for (const item of { a: 1 }) console.log(item);
} catch (error) {
  console.log(error.name);
}

Output:

TypeError

Functions used in this recipe

  • Object.entries — Returns an array of property name and value pairs.
  • Object.keys — Returns an array of an object's property names.
  • Object.values — Returns an array of an object's property values.

Thanks for reading!

Donate to the site — we work hard for you.