Sub topic 10
Looping Over Plain Objects with Object.entries
This chapter assumes you know for...of and destructuring in the loop head, and that you know what enumerable properties are. Plain objects cannot go straight into for...of. Three static methods turn an object into an array, and arrays are iterable.
Why a plain object fails in for...of
for...of needs an iterable, meaning an object with a Symbol.iterator method. Arrays, strings, Maps and Sets have one. Object literals do not, so the loop throws before its first iteration:
const scores = { ada: 9, alan: 7 };
try {
for (const v of scores) {}
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message); // scores is not iterable
}Three adapters: keys, values, entries
| Method | Returns | Typical loop head |
|---|---|---|
| `Object.keys(obj)` | array of key strings | `for (const key of Object.keys(obj))` |
| `Object.values(obj)` | array of values | `for (const value of Object.values(obj))` |
| `Object.entries(obj)` | array of `[key, value]` pairs | `for (const [key, value] of Object.entries(obj))` |
All three return only own, enumerable, string-keyed properties. Inherited properties never show up, so the Object.hasOwn check that for...in needs is not required here. Symbol keys are skipped too. The order follows the same rules as for...in: integer-like keys come first in ascending order, then the other keys in insertion order.
Working with entries
Destructuring the pair in the loop head gives you named variables for the key and the value:
const scores = { ada: 9, alan: 7 };
for (const [name, score] of Object.entries(scores)) {
console.log(name, score);
}
// ada 9
// alan 7If you only need the values, Object.values is simpler:
const scores = { ada: 9, alan: 7, grace: 10 };
let total = 0;
for (const score of Object.values(scores)) {
total += score;
}
console.log(total); // 26To transform an object, map over its entries and rebuild it with Object.fromEntries:
const prices = { apple: 1.2, pear: 0.8 };
const doubled = Object.fromEntries(
Object.entries(prices).map(([fruit, price]) => [fruit, price * 2])
);
console.log(doubled); // { apple: 2.4, pear: 1.6 }Common errors
- Writing
for (const [k, v] of obj)without callingObject.entriesgives a TypeError, because the object itself is not iterable. - Writing
for (const k, v of ...)without brackets is a syntax error. You must destructure the pair with[k, v]. - Expecting a Map's entries from
Object.entries(map). A Map stores its data outside its properties, so you get[]. Iterate the Map directly instead. - Expecting numeric keys as numbers. Keys are always strings, so
'1' + 1gives'11'.
Exercise
Given const stock = { pens: 0, pads: 4, ink: 0 };, write a for...of loop that logs the name of every item with a count of zero. Which method do you use, and why not for...in?
Show answer
for (const [item, count] of Object.entries(stock)) { if (count === 0) console.log(item); } logs pens and then ink. Object.entries gives you the key and value together and returns only own properties. for...in would also visit enumerable inherited keys, and you would need bracket access to read each value.
Exercise
What does Object.keys({ 10: 'a', b: 'b', 2: 'c' }) return?
Show answer
['2', '10', 'b']. Integer-like keys come first in ascending numeric order, as strings, and then the remaining keys follow in insertion order.