Sub topic 6
Using forEach, map, filter, and reduce on Keys and Entries
Object.keys, Object.values, and Object.entries return ordinary arrays. That means every array method you already know works on an object's data once you have converted it. This chapter covers how forEach, map, filter, reduce, and their relatives behave on keys and entries, and where people usually go wrong with them.
This chapter assumes you can write arrow functions, you know the basic array methods, and you have read the earlier chapters on Object.keys, Object.values, Object.entries, and destructuring [key, value] pairs in a for...of loop.
Why Array Methods Work Here
None of the three static methods give you a special iterator or a live view of the object. Each one builds a new array and hands it back:
| Call | Array element type | Example element |
|---|---|---|
| `Object.keys(obj)` | string | `'alice'` |
| `Object.values(obj)` | whatever the values are | `90` |
| `Object.entries(obj)` | two-element array `[key, value]` | `['alice', 90]` |
Because the result is a real Array, you can call forEach, map, filter, reduce, some, every, find, sort, and the rest on it. You can also chain them, since most of these methods return a new array.
The examples below use one small object:
const scores = { alice: 90, bob: 72, carol: 85 };forEach: Side Effects for Each Property
forEach runs a callback once per element and returns undefined. Use it when you want to do something with each property, such as logging, writing to the DOM, or pushing into another structure, and you do not need a value back.
Over keys, you look up the value with bracket notation:
const scores = { alice: 90, bob: 72, carol: 85 };
Object.keys(scores).forEach((name) => {
console.log(`${name} scored ${scores[name]}`);
});
// alice scored 90
// bob scored 72
// carol scored 85Over entries, you destructure the pair in the parameter list. The callback also receives the index as its second argument, which is handy for numbering:
const scores = { alice: 90, bob: 72, carol: 85 };
Object.entries(scores).forEach(([name, score], index) => {
console.log(`${index + 1}. ${name}: ${score}`);
});
// 1. alice: 90
// 2. bob: 72
// 3. carol: 85The missing-brackets mistake
The most common bug with entries is leaving out the square brackets in the parameter list:
const scores = { alice: 90, bob: 72, carol: 85 };
Object.entries(scores).forEach((name, score) => {
console.log(name, score);
});
// [ 'alice', 90 ] 0
// [ 'bob', 72 ] 1
// [ 'carol', 85 ] 2Without brackets, name receives the whole pair and score receives the array index. Nothing throws an error, so the bug can go unnoticed until a value looks wrong. The fix is ([name, score]) => ...: one parameter, destructured.
You cannot break out of forEach
A return inside a forEach callback only ends that one call, and break is a syntax error there. If you need to stop early, use a for...of loop, or one of the short-circuiting methods covered later in this chapter.
map: One Output per Property
map returns a new array with the same length as the input, where each element is whatever the callback returned. Use it to turn each property into something else.
const scores = { alice: 90, bob: 72, carol: 85 };
const lines = Object.entries(scores).map(
([name, score]) => `${name.toUpperCase()}=${score}`
);
console.log(lines); // ['ALICE=90', 'BOB=72', 'CAROL=85']Notice that the result is an array of strings, not an object. map on entries always gives you an array. If you want an object back, map each entry to a new [key, value] pair and pass the result to Object.fromEntries, which a later chapter covers in detail.
A second common mistake is writing a callback with a block body and forgetting return:
const scores = { alice: 90, bob: 72, carol: 85 };
const broken = Object.values(scores).map((s) => {
s * 2;
});
console.log(broken); // [undefined, undefined, undefined]
const fixed = Object.values(scores).map((s) => s * 2);
console.log(fixed); // [180, 144, 170]filter: Selecting Properties
filter keeps the elements whose callback returns a truthy value. On keys, it answers "which properties match?":
const inventory = { apples: 4, pears: 0, plums: 12, kiwis: 0 };
const outOfStock = Object.keys(inventory).filter((item) => inventory[item] === 0);
console.log(outOfStock); // ['pears', 'kiwis']On entries, you can test the value directly without a lookup. A leading comma in the destructuring pattern skips the key position when you only need the value:
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']The filter step keeps whole pairs, so the following map still has both parts. You decide what to keep only at the end of the chain.
reduce: Folding an Object into One Value
reduce carries an accumulator through every element and returns its final state. That makes it the general tool for sums, maximums, counts, and grouping.
Sums and totals
const scores = { alice: 90, bob: 72, carol: 85 };
const total = Object.values(scores).reduce((sum, s) => sum + s, 0);
const average = total / Object.keys(scores).length;
console.log(total); // 247
console.log(average); // 82.33333333333333Always pass an initial value
If you call reduce without an initial value, it uses the first element as the starting accumulator. That works until the object is empty:
const empty = {};
try {
Object.values(empty).reduce((sum, s) => sum + s);
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log(Object.values(empty).reduce((sum, s) => sum + s, 0)); // 0Objects built from user input or API responses are often empty, so supply the initial value as a habit.
Finding the entry with the largest value
For a maximum, the accumulator can be an entry. Starting from null keeps the empty case safe:
const scores = { alice: 90, bob: 72, carol: 85 };
const best = Object.entries(scores).reduce(
(top, entry) => (top === null || entry[1] > top[1] ? entry : top),
null
);
console.log(best); // ['alice', 90]Grouping into a new object
When the accumulator is an object, reduce can build a structure with different keys from the input:
const scores = { alice: 90, bob: 72, carol: 85 };
const groups = Object.entries(scores).reduce((acc, [name, score]) => {
const grade = score >= 80 ? 'pass' : 'fail';
if (!acc[grade]) {
acc[grade] = [];
}
acc[grade].push(name);
return acc;
}, {});
console.log(groups); // { pass: ['alice', 'carol'], fail: ['bob'] }Remember to return acc at the end of a block-bodied callback. If you forget, the next iteration receives undefined and throws when it tries to read a property from it.
some, every, and find: Stopping Early
These three methods stop as soon as they know the answer. That makes them the array-method way to get the early exit that forEach cannot do.
const scores = { alice: 90, bob: 72, carol: 85 };
const anyFailing = Object.values(scores).some((s) => s < 75);
const allPositive = Object.values(scores).every((s) => s > 0);
const firstHigh = Object.entries(scores).find(([, s]) => s > 80);
const missing = Object.entries(scores).find(([, s]) => s > 100);
console.log(anyFailing); // true
console.log(allPositive); // true
console.log(firstHigh); // ['alice', 90]
console.log(missing); // undefinedfind on entries returns the whole pair, so you can destructure it afterwards. Check for undefined first, because destructuring undefined throws:
const scores = { alice: 90, bob: 72, carol: 85 };
const match = Object.entries(scores).find(([, s]) => s > 100);
if (match) {
const [name, score] = match;
console.log(name, score);
} else {
console.log('no match'); // no match
}Chaining a Full Pipeline
Each method returns a fresh array, so you can build a pipeline step by step. Here entries are filtered, ranked, and formatted:
const scores = { alice: 90, bob: 72, carol: 85, dave: 78 };
const ranking = Object.entries(scores)
.filter(([, score]) => score >= 75)
.sort(([, a], [, b]) => b - a)
.map(([name, score], i) => `${i + 1}. ${name} (${score})`);
console.log(ranking);
// ['1. alice (90)', '2. carol (85)', '3. dave (78)']sort changes the array it is called on, but here that array is the temporary one created by filter, so the original object is untouched. Calling sort directly on a shared array is a different matter. In that case, copy it first or use toSorted (ES2023).
Also note that the i in the final map is the position after filtering and sorting, not the property's position in the original object.
Choosing Between a Loop and Array Methods
| Need | Good fit | Why |
|---|---|---|
| Run side effects, possibly `await` or `break` | `for...of` over keys or entries | Supports `break`, `continue`, and `await` in order |
| Run side effects, no early exit | `forEach` | Short, reads clearly in a chain |
| Turn each property into a new value | `map` | Returns an array of the same length |
| Keep some properties | `filter` | Returns the matching subset |
| Combine everything into one result | `reduce` | Accumulator can be any type |
| Yes/no question or first match | `some`, `every`, `find` | Stops as soon as the answer is known |
Two practical notes:
forEachdoes not wait for promises.Object.keys(obj).forEach(async (k) => { await save(k); })starts every call at once and returns before any of them finish. Usefor...ofwithawaitwhen the calls must run one after another, orawait Promise.all(Object.keys(obj).map(save))when they can run in parallel.- Every step in a chain allocates a new array. For everyday objects this cost does not matter. If a profiler shows a chain inside a hot loop over very large objects, rewrite it as a single
for...ofloop.
Exercise
Given const stock = { apples: 4, pears: 0, plums: 12, kiwis: 0 }, write one expression that returns the total number of items in stock, and another that returns the names of in-stock items sorted alphabetically.
Show answer
Total: Object.values(stock).reduce((sum, n) => sum + n, 0) gives 16. Names: Object.entries(stock).filter(([, n]) => n > 0).map(([name]) => name).sort() gives ['apples', 'plums']. The initial value 0 keeps the reduce safe if stock is empty.
Exercise
A teammate writes Object.entries(prices).map((item, price) => ${item}: $${price}) for const prices = { tea: 3, cake: 5 }. What does it return, and how do you fix it?
Show answer
It returns ['tea,3: $0', 'cake,5: $1'], because item receives the whole [key, value] array (which becomes 'tea,3' inside the template literal) and price receives the index. Fix it by destructuring the single parameter: Object.entries(prices).map(([item, price]) => ${item}: $${price}), which returns ['tea: $3', 'cake: $5'].
Exercise
Using reduce on Object.entries, count how many people in const ages = { ann: 17, ben: 34, cy: 15, dee: 52 } are minors (under 18) and how many are adults, returning { minor: 2, adult: 2 }.
Show answer
Object.entries(ages).reduce((acc, [, age]) => { const k = age < 18 ? 'minor' : 'adult'; acc[k] = (acc[k] || 0) + 1; return acc; }, {}). The key is skipped with a leading comma, the accumulator starts as an empty object, and the callback must return acc.