Sub topic 11
Applying map, filter, and reduce to Objects
This chapter assumes you already know how map, filter, and reduce work on arrays and how to chain them. You should also be comfortable with array destructuring in function parameters, such as ([key, value]) => ....
Plain objects have no map, filter, or reduce methods. Calling prices.map(...) on an object throws a TypeError. The usual fix is to turn the object into an array, transform that array, and then turn the result back into an object if you need one.
The Round Trip: entries, Transform, fromEntries
Object.entries(obj) returns an array of [key, value] pairs for the object's own enumerable string-keyed properties. Object.fromEntries(pairs) does the reverse. It takes an iterable of [key, value] pairs and builds a new object from them.
Because the middle of the pipeline is an ordinary array, every array method works there:
const prices = { apple: 1, pear: 2, mango: 3 };
const doubled = Object.fromEntries(
Object.entries(prices)
.filter(([, price]) => price > 1)
.map(([fruit, price]) => [fruit, price * 2])
);
console.log(doubled); // { pear: 4, mango: 6 }
console.log(prices); // { apple: 1, pear: 2, mango: 3 } (original unchanged)The leading comma in ([, price]) skips the key, since the filter only needs the value. The map callback has to return a two-element array. If it returns only price * 2, fromEntries throws, because a number is not an entry.
Choosing keys, values, or entries
You don't always need both halves of each pair. Pick the narrowest method for the job:
| Method | Returns | Use when |
|---|---|---|
| `Object.keys(obj)` | `['apple', 'pear']` | You only need property names |
| `Object.values(obj)` | `[1, 2]` | You only need the values, for example to sum them |
| `Object.entries(obj)` | `[['apple', 1], ['pear', 2]]` | You need both, or you plan to rebuild an object |
To aggregate the values, you don't need a round trip at all:
const cart = { apple: 1.5, pear: 2, mango: 3.25 };
const total = Object.values(cart).reduce((sum, price) => sum + price, 0);
console.log(total); // 6.75
const expensive = Object.keys(cart).filter(name => cart[name] > 1.75);
console.log(expensive); // ['pear', 'mango']Renaming and reshaping keys
The map step can change keys as well as values. Here reduce is skipped and map renames each key:
const config = { db_host: 'localhost', db_port: 5432 };
const camel = Object.fromEntries(
Object.entries(config).map(([key, value]) => [
key.replace(/_(\w)/g, (_, ch) => ch.toUpperCase()),
value
])
);
console.log(camel); // { dbHost: 'localhost', dbPort: 5432 }If two entries map to the same key, the later one silently overwrites the earlier one. Check for collisions when a key transform can produce duplicates.
Working with Maps
A Map is already iterable as [key, value] pairs, so you can spread it into an array and pass the result to new Map(...):
const stock = new Map([['apple', 0], ['pear', 4]]);
const inStock = new Map([...stock].filter(([, qty]) => qty > 0));
console.log(inStock); // Map(1) { 'pear' => 4 }Object.fromEntries(map) and new Map(Object.entries(obj)) convert between the two forms.
Exercise
Given const scores = { ana: 72, ben: 45, cy: 88 }, write one expression that returns a new object containing only scores of 50 or more, with each score converted to a string ending in '%' (for example '72%').
Show answer
Object.fromEntries(Object.entries(scores).filter(([, s]) => s >= 50).map(([name, s]) => [name, ${s}%])) returns { ana: '72%', cy: '88%' } and leaves scores unchanged.
Exercise
Why does Object.fromEntries(Object.entries({ a: 1, b: 2 }).map(([k, v]) => v * 10)) throw, and how do you fix it?
Show answer
The map callback returns plain numbers, and Object.fromEntries needs each item to be a [key, value] entry, so it throws a TypeError. Return a pair instead: .map(([k, v]) => [k, v * 10]).