Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Iterating objects and Object functions

An object has no map() or forEach() methods like an array does. Instead there are the built-in functions Object.keys(), Object.values() and Object.entries(): they turn an object into an array, and with an array you can do everything you already know.

Object.keys — property names

Object.keys() returns an array of the object's keys in the order the properties were added:

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

Object.values — the values

Object.values() returns an array of values. It is handy when the names do not matter — for example, to add up all the numbers:

const expenses = { food: 300, transport: 120, cinema: 80 };
 
const total = Object.values(expenses).reduce((sum, value) => sum + value, 0);
 
console.log(total); // 500

Object.entries — pairs

Object.entries() returns an array of [key, value] pairs. In a for...of loop each pair is unpacked into two variables right away — this syntax is called destructuring and has a lesson of its own:

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

Object.fromEntries — back to an object

Object.fromEntries() does the opposite: it builds an object from an array of pairs. Together with entries() this lets you process an object with array methods:

const prices = { tea: 5, coffee: 12 };
 
const doubled = Object.fromEntries(
  Object.entries(prices).map(([key, value]) => [key, value * 2]),
);
 
console.log(doubled.coffee); // 24

The for...in loop

The for...in loop goes over the object's keys directly, without an intermediate array:

const user = { name: 'Anna', age: 25 };
 
for (const key in user) {
  console.log(key, user[key]);
}
// name Anna
// age 25

To check whether an object has its own property, use Object.hasOwn(user, 'age') — it returns true or false.

FunctionReturns
Object.keys(obj)an array of keys
Object.values(obj)an array of values
Object.entries(obj)an array of [key, value] pairs
Object.fromEntries(pairs)a new object from pairs

Common mistake

An object has no length property, and reading it returns undefined. The number of properties is the length of the array of keys:

const user = { name: 'Anna', age: 25 };
 
console.log(user.length);              // undefined
console.log(Object.keys(user).length); // 2

Thanks for reading!

Donate to the site — we work hard for you.