Sub topic 11
Applying map, filter, and reduce to Objects
Plain objects hold a lot of real data: configuration settings, price lists, counts keyed by name, API responses. Arrays have map, filter, and reduce, but objects do not. This chapter shows how to turn an object into an array, run the usual methods on it, and turn the result back into an object.
This chapter assumes you are comfortable with map, filter, reduce, and method chaining from earlier chapters. You should also know array destructuring (const [a, b] = pair) and object spread ({ ...obj }).
Why Objects Have No map Method
map, filter, and reduce live on Array.prototype. A plain object inherits from Object.prototype, which has none of them. Calling prices.map(...) on an object throws a TypeError because prices.map is undefined.
const prices = { apple: 1, pear: 2, mango: 3 };
try {
prices.map(p => p * 2);
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message); // prices.map is not a function
}The fix is a conversion step rather than a new method. JavaScript gives you three functions that read an object into an array, and one that builds an object from an array.
The Bridge Functions
| Function | Returns | Use it when you need |
|---|---|---|
| `Object.keys(obj)` | `['apple', 'pear', 'mango']` | Only the property names |
| `Object.values(obj)` | `[1, 2, 3]` | Only the values |
| `Object.entries(obj)` | `[['apple', 1], ['pear', 2], ['mango', 3]]` | Both, as `[key, value]` pairs |
| `Object.fromEntries(iterable)` | `{ apple: 1, pear: 2, mango: 3 }` | To rebuild an object from pairs |
Object.entries and Object.fromEntries are inverses for ordinary data objects. Put them around an array pipeline and you can transform an object the same way you transform an array.
The Basic Round Trip
Here is the full pattern. It keeps prices above 1 and doubles them:
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 } (unchanged)Two details matter here.
- Each element the callbacks receive is a two-element array. Destructuring in the parameter list (
([fruit, price]) => ...) names both parts. The leading comma in([, price])skips the key when you only need the value. - The
mapcallback must return a pair[key, value]. If it returns onlyprice * 2,Object.fromEntriesthrows aTypeErrorbecause a number is not an entry.
Transforming Keys Instead of Values
The returned pair can change the key as well as the value. This makes renaming and prefixing easy:
const settings = { theme: 'dark', fontSize: 14 };
const prefixed = Object.fromEntries(
Object.entries(settings).map(([key, value]) => [`user_${key}`, value])
);
console.log(prefixed); // { user_theme: 'dark', user_fontSize: 14 }Swapping the pair inverts an object. Keep in mind that keys are always strings (or symbols), so number values become string keys:
const statusCodes = { ok: 200, notFound: 404 };
const byCode = Object.fromEntries(
Object.entries(statusCodes).map(([name, code]) => [code, name])
);
console.log(byCode); // { '200': 'ok', '404': 'notFound' }
console.log(byCode[404]); // 'notFound' (404 is coerced to '404')Using reduce on Objects
When the result is a single value rather than another object, skip fromEntries and reduce directly. Object.values is often enough:
const cart = { apple: 3, pear: 1, mango: 2 };
const itemCount = Object.values(cart).reduce((sum, qty) => sum + qty, 0);
console.log(itemCount); // 6You can also reduce entries into a new object. This does the same job as fromEntries and is useful when one entry can produce several properties or none:
const inventory = { apple: 0, pear: 5, mango: 2 };
const inStock = Object.entries(inventory).reduce((acc, [fruit, qty]) => {
if (qty > 0) acc[fruit] = qty;
return acc;
}, {});
console.log(inStock); // { pear: 5, mango: 2 }Mutating acc here is safe. The {} initial value is a fresh object that only this reduce call owns, so nothing outside it sees the mutation.
A Reusable mapValues Helper
Changing every value while keeping every key is the most common object transformation. A small helper keeps call sites short:
function mapValues(obj, fn) {
return Object.fromEntries(
Object.entries(obj).map(([key, value]) => [key, fn(value, key)])
);
}
const celsius = { monday: 20, tuesday: 25 };
const fahrenheit = mapValues(celsius, c => c * 9 / 5 + 32);
console.log(fahrenheit); // { monday: 68, tuesday: 77 }The helper passes the key as a second argument, the same way map passes the index. Callers that don't need it can ignore it.
Converting Between Objects and Maps
Object.fromEntries accepts any iterable of pairs, not only arrays. A Map iterates as [key, value] pairs, so conversion works in both directions:
const scores = { ada: 90, grace: 95 };
const scoreMap = new Map(Object.entries(scores));
scoreMap.set('linus', 88);
const backToObject = Object.fromEntries(scoreMap);
console.log(backToObject); // { ada: 90, grace: 95, linus: 88 }This helps when a library hands you a Map but you need a JSON-serializable object. JSON.stringify on a Map produces {}, so convert it first.
Edge Cases That Change Results
Object.entries does not return every property an object has. Know its rules before you depend on it.
Only Own, Enumerable, String-Keyed Properties
Inherited properties, non-enumerable properties, and symbol keys are all skipped:
const id = Symbol('id');
const base = { inherited: true };
const obj = Object.create(base);
obj.name = 'widget';
obj[id] = 42;
Object.defineProperty(obj, 'hidden', { value: 'secret', enumerable: false });
console.log(Object.entries(obj)); // [['name', 'widget']]
console.log(obj.inherited, obj[id], obj.hidden); // true 42 'secret'After a round trip through entries and fromEntries, the new object has lost its prototype, its symbol keys, and its non-enumerable properties. For plain data from JSON this never matters. For class instances it matters a lot: the result is a plain object with no methods.
class Point {
constructor(x, y) { this.x = x; this.y = y; }
length() { return Math.hypot(this.x, this.y); }
}
const p = new Point(3, 4);
const scaled = Object.fromEntries(
Object.entries(p).map(([k, v]) => [k, v * 2])
);
console.log(scaled); // { x: 6, y: 8 }
console.log(scaled instanceof Point); // false
console.log(typeof scaled.length); // 'undefined'Key Order
Entries come out in a defined order. Keys that look like non-negative integers come first, in ascending numeric order. All other string keys follow in insertion order.
const mixed = { b: 1, 2: 'two', a: 2, 1: 'one' };
console.log(Object.keys(mixed)); // ['1', '2', 'b', 'a']If your output order matters, for example when rendering a list, sort the entries explicitly. Don't rely on how the object was written:
const votes = { rust: 12, go: 30, zig: 7 };
const ranked = Object.entries(votes).sort(([, a], [, b]) => b - a);
console.log(ranked); // [['go', 30], ['rust', 12], ['zig', 7]]Duplicate Keys
If your map produces two pairs with the same key, Object.fromEntries keeps the last one with no warning. This often happens when normalizing keys:
const headers = { 'Content-Type': 'text/html', 'content-type': 'application/json' };
const normalized = Object.fromEntries(
Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v])
);
console.log(normalized); // { 'content-type': 'application/json' }If losing data would be a bug, use reduce and check whether acc already has the key before assigning.
Shallow Copies
The new object is new, but nested values are shared by reference. Mapping ([k, v]) => [k, v] copies the outer object only:
const config = { db: { host: 'localhost' } };
const copy = Object.fromEntries(Object.entries(config));
copy.db.host = 'prod.example.com';
console.log(config.db.host); // 'prod.example.com'To change a nested object without touching the original, copy it inside the callback with { ...v, host: 'new' }, as the immutability chapter describes. Use structuredClone when you need a full deep copy.
Exercises
Exercise
Given const stock = { apple: 0, pear: 4, kiwi: 0, plum: 9 }, write one expression that returns an array of the names of fruits that are out of stock.
Show answer
Object.entries(stock).filter(([, qty]) => qty === 0).map(([name]) => name) returns ['apple', 'kiwi']. Object.keys(stock).filter(name => stock[name] === 0) also works. Since the result is an array, you don't need Object.fromEntries.
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 (10 and 20), but Object.fromEntries needs each element to be a [key, value] pair. Return the pair instead: .map(([k, v]) => [k, v * 10]), which gives { a: 10, b: 20 }.
Exercise
Write a function filterObject(obj, predicate) that returns a new object containing only the entries for which predicate(value, key) is truthy. Then show its result for filterObject({ x: 1, y: -2, z: 3 }, v => v > 0).
Show answer
function filterObject(obj, predicate) { return Object.fromEntries(Object.entries(obj).filter(([key, value]) => predicate(value, key))); } The call returns { x: 1, z: 3 }.
Exercise
You run const out = Object.fromEntries(Object.entries(user)) where user is an instance of a User class with a greet() method and a symbol-keyed property. What does out lack compared with user, and why?
Show answer
out is a plain object whose prototype is Object.prototype, so it has no greet() method and instanceof User is false. It also lacks the symbol-keyed property, because Object.entries returns only own, enumerable, string-keyed properties. Any nested objects in out are the same references as in user.