Sub topic 4
Looping over Key-Value Pairs with Object.entries
This chapter assumes you know object literals, bracket notation, arrays, and the for...of loop. It also assumes you have read the earlier chapters on own enumerable properties and Object.keys.
Object.keys gives you names, and Object.values gives you values. Many loops need both at once. For example, you might want to print a report line for each person, or check a value and then record its key. Object.entries returns both together, one pair per property.
What Object.entries returns
Object.entries(obj) returns a new array. Each element of that array is itself a two-element array, [key, value], for one of the object's own enumerable string-keyed properties. It includes the same properties as Object.keys, in the same order.
const scores = { alice: 90, bob: 72, carol: 85 };
const pairs = Object.entries(scores);
console.log(pairs);
// [ [ 'alice', 90 ], [ 'bob', 72 ], [ 'carol', 85 ] ]
console.log(pairs.length); // 3
console.log(pairs[1]); // [ 'bob', 72 ]
console.log(pairs[1][0]); // 'bob'
console.log(pairs[1][1]); // 72Index 0 of each pair is always the key, and index 1 is always the value. The key is always a string, even when the property was written as a number.
Looping over the pairs
The result is an ordinary array, so for...of works on it directly. Each iteration receives one pair.
const scores = { alice: 90, bob: 72, carol: 85 };
for (const pair of Object.entries(scores)) {
const name = pair[0];
const score = pair[1];
console.log(`${name}: ${score}`);
}
// alice: 90
// bob: 72
// carol: 85This works, but pulling out pair[0] and pair[1] by hand gets noisy. JavaScript lets you unpack the pair in the loop head instead:
const scores = { alice: 90, bob: 72, carol: 85 };
for (const [name, score] of Object.entries(scores)) {
console.log(`${name}: ${score}`);
}The output is the same. The next chapter covers this destructuring syntax in detail. For now, read [name, score] as "call the first element name and the second score."
Entries versus keys with a lookup
Both of these loops print the same thing:
const scores = { alice: 90, bob: 72, carol: 85 };
for (const name of Object.keys(scores)) {
console.log(name, scores[name]);
}
for (const [name, score] of Object.entries(scores)) {
console.log(name, score);
}| Approach | Gives you | Good when |
|---|---|---|
| `Object.keys` + `obj[key]` | Key, plus a live lookup | You need the current value at each step, or you write back to `obj[key]` |
| `Object.values` | Values only | Keys are irrelevant, as in sums or counts |
| `Object.entries` | Key and value together | You read both, especially when passing pairs to array methods |
Common errors
Treating a pair as an object
A pair is an array, not an object with key and value fields.
const scores = { alice: 90 };
for (const pair of Object.entries(scores)) {
console.log(pair.key); // undefined
console.log(pair[0]); // 'alice'
}Expecting numeric keys to stay numbers
const byId = { 1: 'Ada', 2: 'Linus' };
for (const [id, name] of Object.entries(byId)) {
console.log(typeof id, id === 1); // 'string' false
}Convert the key with Number(id) if you need to compare it to a number.
Assuming the value tracks later changes
Object.entries copies each value into its pair when you call it. If you reassign a property during the loop, the pair you already hold keeps the old value.
const counts = { a: 1, b: 2 };
for (const [key, value] of Object.entries(counts)) {
counts.b = 100;
console.log(key, value);
}
// a 1
// b 2 (not 100)Exercise
Given const stock = { apples: 0, pears: 4, plums: 0 };, write a for...of loop using Object.entries that logs "Out of stock: apples" and "Out of stock: plums" and nothing for pears.
Show answer
for (const [item, qty] of Object.entries(stock)) { if (qty === 0) { console.log(Out of stock: ${item}); } } Each pair is unpacked into item (the key string) and qty (the value). The check on qty skips pears.
Exercise
What does Object.entries({ 10: 'x', b: 'y' })[0][0] evaluate to, and what is its type?
Show answer
It evaluates to '10', a string. The first pair is ['10', 'x'] because integer-like keys come first, and all keys are returned as strings.