More JavaScript answers

by Danny
Published 2 min read

Plain objects are not iterable, so use Object.entries, Object.keys or Object.values with for...of. Learn which to pick and how to avoid inherited and symbol keys.

The short answer

#

Use Object.entries(obj) with a for...of loop to get each key and value together. Use Object.keys when you only need the keys and Object.values when you only need the values. All three return ordinary arrays, so you can also use map, filter and forEach on them.


_10
const stock = { apples: 12, pears: 0, plums: 7 };
_10
_10
for (const [fruit, count] of Object.entries(stock)) {
_10
console.log(`${fruit}: ${count}`);
_10
}

Why it happens

#

Arrays, strings, Map and Set are iterable, so for...of works on them directly. Plain objects are not. Writing for (const x of obj) throws TypeError: obj is not iterable.

The older for...in loop does work on objects, but it also visits enumerable properties inherited through the prototype chain, which is why older code is full of hasOwnProperty checks. The Object.keys, Object.values and Object.entries methods only return the object's own enumerable string keys, which is almost always what you want.

How to fix it

#

Object.entries for keys and values

Destructure each [key, value] pair in the loop.


_10
const headers = { 'Content-Type': 'application/json', Accept: 'text/html' };
_10
_10
for (const [name, value] of Object.entries(headers)) {
_10
request.setHeader(name, value);
_10
}

To transform an object, map over its entries and rebuild it with Object.fromEntries.


_10
const prices = { tea: 2.5, coffee: 3, cake: 4.25 };
_10
_10
const withVat = Object.fromEntries(
_10
Object.entries(prices).map(([item, price]) => [item, price * 1.2]),
_10
);

Object.keys when you only need keys


_10
const user = { id: 1, name: 'Ada', email: '[email protected]' };
_10
_10
Object.keys(user); // ['id', 'name', 'email']
_10
Object.keys(user).length; // 3

Object.values when you only need values


_10
const totals = { january: 120, february: 95, march: 140 };
_10
_10
const sum = Object.values(totals).reduce((a, b) => a + b, 0); // 355
_10
const hasZero = Object.values(stock).includes(0); // true

for...in with Object.hasOwn

If you do use for...in, guard it with Object.hasOwn, the modern replacement for hasOwnProperty.


_10
for (const key in obj) {
_10
if (Object.hasOwn(obj, key)) {
_10
console.log(key, obj[key]);
_10
}
_10
}

Use a Map for data you loop over a lot

If you are using an object as a dictionary that you add to, remove from and iterate, a Map is often a better fit. It is iterable directly, keeps insertion order, and allows keys of any type.


_10
const scores = new Map([
_10
['ada', 10],
_10
['grace', 12],
_10
]);
_10
_10
for (const [name, score] of scores) {
_10
console.log(name, score);
_10
}

Common pitfalls

#
  • Key order. Keys that look like whole numbers, such as '2' and '10', come first in ascending numeric order, then the other string keys in the order they were added. Do not rely on order for meaning; sort the entries if it matters.
  • Keys are always strings. Even if you wrote { 1: 'a' }, the key you get back is '1'. Convert with Number(key) if needed.
  • Symbol and non-enumerable keys are skipped. None of these methods return them. Use Reflect.ownKeys(obj) if you really need every own key.
  • Changing the object while looping. Adding keys inside a loop over Object.keys does not visit the new ones, because the array was made before the loop started. That is usually fine, but avoid relying on it.
  • Async work in forEach. Object.entries(obj).forEach(async ...) does not wait for anything. Use for...of with await, or Promise.all over a map.
  • Nested objects. These methods only look one level deep. Recurse, or flatten the data first, if you need to visit nested values.
#

Was this resource helpful?