Sub topic 2
Looping over Keys with Object.keys
This chapter assumes you know JavaScript variables and arrow functions, object literals with dot and bracket notation, and arrays with the for...of loop. It also assumes you have read the previous chapter on own enumerable properties. Here you learn the most basic way to loop over a plain object: get its keys as an array, then loop over that array.
The working model
A plain object is not iterable. If you write for (const x of someObject), JavaScript throws a TypeError because objects have no built-in iterator. Object.keys solves this. It takes an object and returns a new, ordinary array of the object's own enumerable string keys. Arrays are iterable, so for...of can loop over the result.
The pattern has two steps:
- Call
Object.keys(obj)to get an array of key strings. - Loop over that array, and use bracket notation (
obj[key]) to read each value.
A first loop
const scores = { alice: 90, bob: 72, carol: 85 };
for (const name of Object.keys(scores)) {
console.log(name, scores[name]);
}
// alice 90
// bob 72
// carol 85On each pass, name holds one key as a string. scores[name] looks up the value for that key. You must use bracket notation here. scores.name would look for a property literally called "name" and return undefined.
The result is a real array
Object.keys returns an ordinary Array, so everything that works on arrays works on it:
const user = { id: 17, name: 'Ada', role: 'admin' };
const keys = Object.keys(user);
console.log(keys.length); // 3
console.log(keys.includes('role')); // true
console.log(keys.join(', ')); // id, name, role
console.log(Array.isArray(keys)); // trueThis means you can answer questions about an object without writing a loop at all. Checking for an empty object is a common case:
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
console.log(isEmpty({})); // true
console.log(isEmpty({ a: 1 })); // falseLater chapters build on this by calling forEach, map, filter, and reduce on the key array.
Keys are always strings
Property keys come back as strings, even if you wrote them as numbers in the literal:
const seats = { 1: 'Ana', 2: 'Ben' };
for (const seat of Object.keys(seats)) {
console.log(typeof seat, seat);
}
// string 1
// string 2If you need numbers, convert them yourself with Number(seat). Otherwise a comparison such as seat === 1 will be false.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| `for (const k of obj)` | `TypeError: obj is not iterable` | Loop over `Object.keys(obj)` |
| `obj.key` inside the loop | Reads a property named `"key"`, usually `undefined` | Use `obj[key]` |
| `for (const k in Object.keys(obj))` | `k` is the array index (`'0'`, `'1'`), not the key | Use `for...of`, not `for...in`, over the array |
| Comparing a key to a number with `===` | Always `false`, because keys are strings | Compare to a string, or convert with `Number()` |
The third row catches many people. for...in over an array gives you its indexes. Use of to get its elements.
Why a snapshot matters
Object.keys builds its array once, at the moment you call it. Properties added to the object after the call do not appear in that array. Most of the time this does not matter. It does mean that the keys you loop over are fixed when the loop starts. The last chapter in this tutorial uses this to delete properties safely while looping.
const config = { a: 1 };
const keys = Object.keys(config);
config.b = 2;
console.log(keys); // ['a']
console.log(Object.keys(config)); // ['a', 'b']Exercise
Write a function countLongKeys(obj, min) that returns how many of the object's own enumerable keys have at least min characters. For example, countLongKeys({ id: 1, username: 'x', email: 'y' }, 5) should return 2.
Show answer
Get the key array and count the keys that are long enough. One version uses a loop: function countLongKeys(obj, min) { let count = 0; for (const key of Object.keys(obj)) { if (key.length >= min) count++; } return count; }. A shorter version uses an array method: const countLongKeys = (obj, min) => Object.keys(obj).filter(k => k.length >= min).length;. Both work because Object.keys returns a real array of strings.
Exercise
This code prints undefined three times. Why, and how do you fix it? const p = { x: 1, y: 2, z: 3 }; for (const key of Object.keys(p)) { console.log(p.key); }
Show answer
p.key looks up a property literally named "key", and p has no such property. To use the value held in the variable key, change the line to console.log(p[key]);. The loop then prints 1, 2, 3.