Sub topic 2
Destructuring [key, value] in for...of
This chapter assumes you know arrow functions, for...of over arrays, and the array methods forEach, map, filter, and reduce. It also assumes you have seen how Object.keys and Object.entries return arrays.
Destructuring [key, value] in for...of
Object.entries returns an array of two-element arrays. Each inner array holds a key and its value. You could read pair[0] and pair[1], but array destructuring in the loop head names both parts directly:
const scores = { alice: 90, bob: 72, carol: 85 };
for (const [name, score] of Object.entries(scores)) {
console.log(`${name}: ${score}`);
}
// alice: 90
// bob: 72
// carol: 85A common mistake is writing { name, score } instead of [name, score]. Each entry is an array, not an object, so curly-brace destructuring gives you undefined for both names.
Using forEach, map, filter, and reduce on Keys and Entries
Object.keys and Object.entries return ordinary arrays, so every array method works on them. Destructuring also works in arrow-function parameters. To skip a position, leave it empty:
const scores = { alice: 90, bob: 72, carol: 85 };
const passing = Object.entries(scores)
.filter(([, score]) => score >= 80)
.map(([name]) => name);
console.log(passing); // ['alice', 'carol']
const total = Object.entries(scores).reduce((sum, [, score]) => sum + score, 0);
console.log(total); // 247Object.keys versus for...in
A for...in loop also visits keys, but it includes enumerable properties inherited through the prototype chain. Object.keys returns only the object's own properties:
const base = { inherited: true };
const child = Object.create(base);
child.own = 1;
for (const key in child) {
console.log(key);
}
// own
// inherited
console.log(Object.keys(child)); // ['own']| Approach | Own properties | Inherited enumerable | Returns an array |
|---|---|---|---|
| `Object.keys` / `Object.entries` | Yes | No | Yes |
| `for...in` | Yes | Yes | No |
If you use for...in, guard each key with Object.hasOwn(obj, key). In most code, Object.keys or Object.entries with for...of is the simpler choice.
Exercise
Given const stock = { apples: 0, pears: 4, plums: 0 };, write one expression that returns an array of the fruit names whose count is 0.
Show answer
Object.entries(stock).filter(([, count]) => count === 0).map(([fruit]) => fruit) returns ['apples', 'plums'].
Exercise
Why might for (const key in obj) log a key that Object.keys(obj) does not include?
Show answer
for...in also visits enumerable properties inherited from the object's prototype chain. Object.keys returns only the object's own enumerable string keys.