Sub topic 4
Looping over Key-Value Pairs with Object.entries
The previous chapters used Object.keys to get an object's keys and Object.values to get its values. Many loops need both at once: a label and its count, a setting name and its value, a user ID and its record. Object.entries returns both together, as pairs.
This chapter assumes you know variables, arrow functions, object literals, dot and bracket notation, arrays, and the for...of loop. It also assumes you have read the earlier chapters on own enumerable properties and Object.keys.
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. The key is always a string. The value is whatever the property holds.
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[0]); // [ 'alice', 90 ]
console.log(pairs[0][0]); // 'alice'
console.log(pairs[0][1]); // 90The result is an ordinary array of arrays. You can index it, check its length, loop over it, and call array methods on it. Nothing about it is special to objects once it has been created.
Object.entries includes the same properties as Object.keys, in the same order. If Object.keys(obj) returns ['a', 'b'], then Object.entries(obj) returns [['a', obj.a], ['b', obj.b]]. Everything you learned about which properties Object.keys includes carries over directly.
Looping over the Pairs
Because the result is an array, for...of loops over it. Each iteration gives you 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: 85Compare this with the Object.keys version from the earlier chapter:
const scores = { alice: 90, bob: 72, carol: 85 };
for (const name of Object.keys(scores)) {
const score = scores[name];
console.log(`${name}: ${score}`);
}
// alice: 90
// bob: 72
// carol: 85Both print the same output. The difference is where the value comes from. With Object.keys, the loop body reads the value back out of the object with scores[name]. With Object.entries, the value already sits in the pair. The loop body never refers to scores again, so a loop over Object.entries(someLongExpression()) doesn't need a temporary variable to hold the object for lookups.
Writing pair[0] and pair[1] works, but those indexes say nothing about meaning. The usual form unpacks the pair directly in the loop head with array destructuring:
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: 85The next chapter covers this syntax in detail: skipping positions, default values, and nested pairs. For now, read const [name, score] as "name the first element name and the second score."
Choosing Between keys, values, and entries
All three methods visit the same properties in the same order. They differ only in what each array element contains.
| Method | Each element is | Use when the loop needs |
|---|---|---|
| `Object.keys(obj)` | the key, a string | only the keys, or keys used to read or write `obj` |
| `Object.values(obj)` | the value | only the values, such as totals or searches |
| `Object.entries(obj)` | `[key, value]` | both the key and the value |
A simple rule: pick the method whose output matches what the loop body uses. If you write Object.entries and never use the key, Object.values is clearer. If you write Object.keys and immediately read obj[key] on every iteration without writing back, Object.entries is clearer.
There is one case where Object.keys stays the better fit even though you need values. When the loop writes back to the object, such as obj[key] = ... or delete obj[key], the key is the main thing you work with. Reading the value with obj[key] keeps reads and writes in the same form.
Counting and Checking for Empty Objects
Since Object.entries returns an array, its length is the number of own enumerable string-keyed properties. Object.keys(obj).length gives the same number and avoids building the pair arrays, so prefer it when you only need a count.
const empty = {};
const filled = { a: 1 };
console.log(Object.keys(empty).length === 0); // true
console.log(Object.keys(filled).length === 0); // false
console.log(Object.entries(filled).length); // 1Pairs Are Snapshots, Values Are Shared
Object.entries builds its array once, at the moment you call it. Later changes to the object do not appear in that array, and changes to the array do not flow back into the object.
const inventory = { apples: 3, pears: 5 };
const pairs = Object.entries(inventory);
inventory.plums = 7;
inventory.apples = 0;
console.log(pairs);
// [ [ 'apples', 3 ], [ 'pears', 5 ] ]The pair array holds 3 for apples and has no plums, because both changes happened after the call. (A later chapter looks at what this snapshot means when you add or delete properties inside a loop.)
The copy is shallow. A pair holds the same value the property held. For primitives such as numbers and strings, that makes no practical difference. For objects and arrays, the pair and the original property point to the same object.
const config = { db: { host: 'localhost' }, port: 8080 };
const pairs = Object.entries(config);
// Replacing the value in the pair does not touch config.
pairs[1][1] = 9090;
console.log(config.port); // 8080
// Mutating a shared object does.
pairs[0][1].host = 'db.internal';
console.log(config.db.host); // 'db.internal'Getters Run When You Call Object.entries
If a property is defined with a getter, Object.entries calls the getter and stores the result in the pair. The pair holds the computed value at call time, not the getter function.
const temp = {
celsius: 20,
get fahrenheit() {
return this.celsius * 9 / 5 + 32;
}
};
const before = Object.entries(temp);
temp.celsius = 100;
const after = Object.entries(temp);
console.log(before); // [ [ 'celsius', 20 ], [ 'fahrenheit', 68 ] ]
console.log(after); // [ [ 'celsius', 100 ], [ 'fahrenheit', 212 ] ]This matters in two situations. A getter that is slow or has side effects runs once per Object.entries call, even if the loop never reaches that pair. A getter that throws makes the whole Object.entries call throw before your loop starts. Object.keys does not read values, so it never triggers getters.
A Common Mistake: Calling .entries() on a Plain Object
Arrays, Maps, and Sets have an .entries() method. Plain objects do not. This catches people who move between these types.
const scores = { alice: 90, bob: 72 };
try {
scores.entries();
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message); // scores.entries is not a function
}
// The static method is the correct form:
console.log(Object.entries(scores)); // [ [ 'alice', 90 ], [ 'bob', 72 ] ]The two forms also behave differently. Map.prototype.entries() returns an iterator, which is lazy: it produces pairs as you consume them and reflects changes made to the Map during iteration. Object.entries() returns a fully built array. You can call .length, .map, or .filter on the array. You cannot call them directly on a Map iterator in older environments.
| Row | `Object.entries(obj)` | `map.entries()` |
|---|---|---|
| Called as | static function on `Object` | method on a Map instance |
| Returns | an array of `[key, value]` arrays | an iterator of `[key, value]` arrays |
| Keys | always strings | any type |
| Built | all at once, a snapshot | one pair at a time |
Converting an Object to a Map
The pair format from Object.entries matches what the Map constructor accepts. That makes converting an object to a Map a one-liner.
const scores = { alice: 90, bob: 72, carol: 85 };
const scoreMap = new Map(Object.entries(scores));
console.log(scoreMap.get('bob')); // 72
console.log(scoreMap.size); // 3
for (const [name, score] of scoreMap) {
console.log(name, score);
}
// alice 90
// bob 72
// carol 85This is useful when you receive data as a plain object, for example from JSON.parse, and want Map features such as size, frequent additions and deletions, or non-string keys added later. The reverse direction, turning pairs back into a plain object, uses Object.fromEntries, which a later chapter covers.
Nested Objects
Object.entries only looks one level deep. When a value is itself an object, you call Object.entries again on that value.
const team = {
frontend: { alice: 90, bob: 72 },
backend: { carol: 85 }
};
for (const [group, members] of Object.entries(team)) {
for (const [name, score] of Object.entries(members)) {
console.log(`${group}/${name}: ${score}`);
}
}
// frontend/alice: 90
// frontend/bob: 72
// backend/carol: 85The outer loop gives each group and its member object. The inner loop gives each member and their score. Each level is a separate call, and each returns its own snapshot.
Edge Behaviors to Know
Object.entries follows the same rules as Object.keys for unusual inputs. Later chapters examine them, but here is a quick reference:
- Symbol-keyed and non-enumerable properties are left out.
- Inherited properties from the prototype chain are left out.
- Integer-like keys come first in ascending order, then other string keys in insertion order.
Object.entries(null)andObject.entries(undefined)throw a TypeError.- Arrays and strings produce pairs keyed by index strings, such as
['0', 'h'].
Exercise
Given const stock = { pens: 12, ink: 0, paper: 40 };, write a for...of loop using Object.entries that prints "pens: 12", "ink: OUT", "paper: 40", printing OUT when the value is 0.
Show answer
for (const [item, count] of Object.entries(stock)) { console.log(${item}: ${count === 0 ? 'OUT' : count}); } Object.entries returns [['pens', 12], ['ink', 0], ['paper', 40]], and destructuring names each part. The ternary replaces 0 with 'OUT'.
Exercise
What does this code print, and why? const user = { tags: ['a'], age: 30 }; const pairs = Object.entries(user); pairs[0][1].push('b'); pairs[1][1] = 31; console.log(user.tags, user.age);
Show answer
It prints [ 'a', 'b' ] 30. The pair for tags holds a reference to the same array as user.tags, so push changes the original. The pair for age holds the number 30, and assigning 31 to the pair's slot only changes the pair array, not user.age.
Exercise
A loop reads for (const key of Object.keys(prices)) { console.log(key, prices[key]); } and never writes to prices. Which method would make it clearer, and how would you rewrite it?
Show answer
Object.entries, because the loop uses both the key and the value and only reads. Rewrite: for (const [key, price] of Object.entries(prices)) { console.log(key, price); }