Sub topic 6
Using forEach, map, filter, and reduce on Keys and Entries
This chapter assumes you know arrow functions, array destructuring, and the basic array methods forEach, map, filter, and reduce. It also builds on the earlier chapters about Object.keys, Object.values, and Object.entries.
Why array methods work here
A plain object has no map or filter method. Calling scores.map(...) throws TypeError: scores.map is not a function. Object.keys, Object.values, and Object.entries each return an ordinary array, so every array method is available on what they return. In practice you convert the object to an array once and then chain array methods on it.
forEach over keys
forEach runs a callback for each element and returns undefined. Use it for side effects such as logging.
const scores = { alice: 90, bob: 72, carol: 85 };
Object.keys(scores).forEach((name) => {
console.log(name.toUpperCase(), scores[name]);
});
// ALICE 90
// BOB 72
// CAROL 85forEach has no break. If you need to stop early, use a for...of loop or a method that stops by design, such as find or some.
map over entries
map turns each [key, value] pair into something new. Destructuring in the callback's parameter list names both parts directly:
const scores = { alice: 90, bob: 72, carol: 85 };
const lines = Object.entries(scores).map(([name, score]) => `${name} scored ${score}`);
console.log(lines);
// ['alice scored 90', 'bob scored 72', 'carol scored 85']The parentheses around [name, score] are required. An arrow function needs parentheses whenever its parameter is a destructuring pattern.
filter, then map
Chaining filter and map selects some entries and reshapes them. To skip a position you don't need, leave it empty in the pattern:
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']In ([, score]), the leading comma skips the key. In ([name]), the pattern takes only the first element.
reduce to a single result
reduce folds the array into one value. If you only need values, Object.values is the shorter route. Use Object.entries when the answer depends on both the key and the value, for example finding the top scorer:
const scores = { alice: 90, bob: 72, carol: 85 };
const top = Object.entries(scores).reduce(
(best, [name, score]) => (score > best.score ? { name, score } : best),
{ name: null, score: -Infinity }
);
console.log(top); // { name: 'alice', score: 90 }The second argument is the initial value. Without it, reduce on an empty object's entries throws TypeError: Reduce of empty array with no initial value.
Stopping early with find and some
find returns the first matching pair and stops looking after that. some returns true as soon as one element matches.
const scores = { alice: 90, bob: 72, carol: 85 };
const firstFail = Object.entries(scores).find(([, score]) => score < 80);
console.log(firstFail); // ['bob', 72]
const anyPerfect = Object.values(scores).some((score) => score === 100);
console.log(anyPerfect); // falseCommon errors
| Mistake | Symptom | Fix |
|---|---|---|
| Calling `.map` on the object itself | `TypeError: ... is not a function` | Call `Object.entries(obj).map(...)` |
| Braces in `map` without `return` | Array of `undefined` | Add `return`, or drop the braces |
| `([k, v]) =>` written as `[k, v] =>` | `SyntaxError` | Wrap the pattern in parentheses |
| `reduce` with no initial value | Throws on an empty object | Pass a starting value |
| Expecting `map` to return an object | You get an array of pairs | Rebuild the object (covered in a later chapter) |
Exercise
Given const stock = { apples: 0, pears: 12, plums: 3, figs: 0 };, write one expression that returns the names of the items that are out of stock, using Object.entries, filter, and map.
Show answer
Object.entries(stock).filter(([, count]) => count === 0).map(([name]) => name) returns ['apples', 'figs']. The filter callback skips the key with a leading comma, and the map callback keeps only the key.
Exercise
Using reduce on Object.entries, compute the total number of items in stock above, but count only items whose name is longer than 4 characters. Why should you pass an initial value?
Show answer
Object.entries(stock).reduce((sum, [name, count]) => (name.length > 4 ? sum + count : sum), 0) returns 12. The names longer than 4 characters are apples (0), pears (12), and plums (0 + 3 would apply, but "plums" has exactly 5 characters, so it counts too), giving 0 + 12 + 3 = 15. The correct answer is therefore 15. The initial value 0 sets the accumulator to a number. Without it, the first accumulator would be the pair ['apples', 0], which gives a wrong result, and an empty object would throw a TypeError.