Sub topic 10
Looping Over Plain Objects with Object.entries
This chapter assumes you already know how for...of walks the values of an iterable and how array destructuring works in a loop head. It also assumes you know what makes a property enumerable and how for...in picks up inherited keys. Here you combine those ideas to loop over ordinary objects, which for...of cannot do on its own.
Why plain objects need a helper
A plain object such as { ada: 9 } has no Symbol.iterator method, so for...of rejects it:
const scores = { ada: 9, alan: 7 };
try {
for (const v of scores) {
console.log(v);
}
} catch (err) {
console.log(err instanceof TypeError, err.message);
}
// true scores is not iterableThis is deliberate. An object can be read in several ways: by its keys, by its values, or by its key-value pairs. JavaScript doesn't pick one for you. Instead, three static methods turn an object into an array, and arrays are iterable:
| Method | Returns | Example result for `{ a: 1, b: 2 }` |
|---|---|---|
| `Object.keys(obj)` | Array of key strings | `['a', 'b']` |
| `Object.values(obj)` | Array of values | `[1, 2]` |
| `Object.entries(obj)` | Array of `[key, value]` pairs | `[['a', 1], ['b', 2]]` |
All three return only own, enumerable, string-keyed properties. Inherited properties, non-enumerable properties and symbol keys are left out.
The core pattern
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 7
for (const name of Object.keys(scores)) {
console.log(name);
}
// ada
// alan
let total = 0;
for (const score of Object.values(scores)) {
total += score;
}
console.log(total); // 16Pick the narrowest method for the job. If you only need values, Object.values reads more clearly than taking Object.entries apart and ignoring the key.
How this differs from for...in
for...in and Object.entries visit keys in the same order: integer-like keys in ascending numeric order first, then other string keys in insertion order. The difference is inheritance. Object.entries never looks up the prototype chain, so you don't need an Object.hasOwn check:
const base = { shared: true };
const obj = Object.create(base);
obj.own = 1;
for (const key in obj) {
console.log('for...in:', key);
}
// for...in: own
// for...in: shared
for (const [key, value] of Object.entries(obj)) {
console.log('entries:', key, value);
}
// entries: own 1What gets left out
Symbol keys and non-enumerable properties are skipped. If you need every own key, use Reflect.ownKeys:
const id = Symbol('id');
const record = { name: 'Ada', [id]: 42 };
Object.defineProperty(record, 'secret', { value: 'x', enumerable: false });
console.log(Object.keys(record)); // ['name']
console.log(Object.entries(record)); // [['name', 'Ada']]
console.log(Reflect.ownKeys(record)); // ['name', 'secret', Symbol(id)]Class instances follow the same rules. Methods are defined on the prototype, so they don't appear. Only instance fields do:
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
length() {
return Math.hypot(this.x, this.y);
}
}
console.log(Object.entries(new Point(3, 4))); // [['x', 3], ['y', 4]]The array is a snapshot
Object.entries builds its whole array before the loop starts. Changes you make to the object during the loop don't change which pairs you visit, and the values you see are the ones that were there when the snapshot was taken:
const config = { a: 1, b: 2 };
for (const [key, value] of Object.entries(config)) {
config.c = 3; // added during the loop: not visited
config.b = 99; // changed during the loop: old value already captured
console.log(key, value);
}
// a 1
// b 2
console.log(config); // { a: 1, b: 99, c: 3 }This makes the behavior predictable, but you pay for it. On a large object, every loop allocates one array plus one small array per pair. That is fine in almost all application code. In a tight inner loop over a very large object, for...in with Object.hasOwn, or a Map, can be cheaper. Measure before you switch.
Transforming objects with Object.fromEntries
Object.fromEntries does the reverse of Object.entries: it builds an object from an iterable of pairs. Together they let you map or filter an object:
const pricesInCents = { apple: 120, pear: 80, plum: 45 };
const doubled = Object.fromEntries(
Object.entries(pricesInCents).map(([fruit, cents]) => [fruit, cents * 2])
);
console.log(doubled); // { apple: 240, pear: 160, plum: 90 }
const cheap = {};
for (const [fruit, cents] of Object.entries(pricesInCents)) {
if (cents < 100) cheap[fruit] = cents;
}
console.log(cheap); // { pear: 80, plum: 45 }Because Object.fromEntries accepts any iterable of pairs, it also converts a Map straight back to an object: Object.fromEntries(myMap).
Common errors and edge cases
| Mistake or input | What happens | Fix |
|---|---|---|
| `for (const v of obj)` | `TypeError: obj is not iterable` | Wrap with `Object.values` or `Object.entries` |
| `for (const pair of Object.entries(obj))` then using `pair` as a key | `pair` is an array like `['a', 1]` | Destructure: `const [key, value]` |
| `for (const [k, v] of Object.keys(obj))` | Destructures each key *string*, so `k` and `v` are its first two characters | Use `Object.entries` |
| `Object.entries(null)` or `undefined` | `TypeError: Cannot convert undefined or null to object` | Guard with `obj ?? {}` |
| `Object.entries('hi')` | `[['0', 'h'], ['1', 'i']]`, since primitives are wrapped | Usually a sign the input type is wrong |
| Numeric keys like `{ 10: 'x', 2: 'y' }` | Keys come back as strings, sorted numerically: `'2'`, `'10'` | Convert with `Number(key)` if needed |
The destructuring mistake with Object.keys doesn't throw an error, which makes it easy to miss:
const user = { name: 'Ada', role: 'admin' };
for (const [k, v] of Object.keys(user)) {
console.log(k, v);
}
// n a
// r oExercise
Given const inventory = { apples: 3, pears: 0, plums: 5 };, write a for...of loop using Object.entries that logs only the items with a count above zero, as "apples: 3". Then build a new object containing only those items with Object.fromEntries.
Show answer
Loop: for (const [item, count] of Object.entries(inventory)) { if (count > 0) console.log(${item}: ${count}); } logs "apples: 3" and "plums: 5". Object: const inStock = Object.fromEntries(Object.entries(inventory).filter(([, count]) => count > 0)); produces { apples: 3, plums: 5 }. The leading comma in [, count] skips the key.
Exercise
An object is created with const child = Object.create({ inherited: 1 }); child.b = 2; child[5] = 'five'; child.a = 3;. What do Object.entries(child) and a for...in loop over child produce, and in what order?
Show answer
Object.entries(child) returns [['5', 'five'], ['b', 2], ['a', 3]]: the integer-like key '5' comes first, then 'b' and 'a' in insertion order, and the inherited key is excluded. A for...in loop visits '5', 'b', 'a', and then 'inherited', because for...in also walks enumerable properties on the prototype chain.