Sub topic 9
Building New Objects with Object.fromEntries
This chapter assumes you already know how Object.entries returns [key, value] pairs and how to destructure those pairs inside map and filter callbacks. Here you go one step further and turn the pairs back into an object.
The Missing Return Trip
Object.entries converts an object into an array. That conversion lets you use array methods on the object's contents, but the result is still an array. Often you want an object back: the same keys with adjusted values, or a subset of the original keys.
Object.fromEntries does the reverse of Object.entries. It takes an iterable of [key, value] pairs and builds a new plain object from them.
const pairs = [['apple', 1.2], ['pear', 0.8]];
const fruit = Object.fromEntries(pairs);
console.log(fruit); // { apple: 1.2, pear: 0.8 }The Entries, Transform, fromEntries Pattern
Most uses of Object.fromEntries follow three steps. First you break the object into pairs, then you reshape the pairs with array methods, and finally you rebuild an object.
Changing Every Value
Use map to change the values and return a new pair from each callback.
const prices = { apple: 1.2, pear: 0.8, plum: 2 };
const discounted = Object.fromEntries(
Object.entries(prices).map(([fruit, price]) => [fruit, price * 0.5])
);
console.log(discounted); // { apple: 0.6, pear: 0.4, plum: 1 }
console.log(prices); // { apple: 1.2, pear: 0.8, plum: 2 }The original prices object is untouched. You get a new object, which makes this pattern a good fit for code that avoids mutation.
Keeping Only Some Properties
Use filter to drop pairs. The callback decides which keys survive.
const user = { name: 'Ada', email: '[email protected]', password: 'hunter2' };
const safeUser = Object.fromEntries(
Object.entries(user).filter(([key]) => key !== 'password')
);
console.log(safeUser); // { name: 'Ada', email: '[email protected]' }Renaming Keys
The callback can change the key as well as the value.
const env = { db_host: 'localhost', db_port: 5432 };
const config = Object.fromEntries(
Object.entries(env).map(([key, value]) => [key.replace('db_', ''), value])
);
console.log(config); // { host: 'localhost', port: 5432 }Common Errors
Returning the Wrong Shape from map
Each element you pass to Object.fromEntries must be a pair. If your map callback returns a bare value, you get a TypeError.
const prices = { apple: 1.2, pear: 0.8 };
try {
Object.fromEntries(Object.entries(prices).map(([, price]) => price * 2));
} catch (err) {
console.log(err instanceof TypeError); // true
}The fix is to return [key, newValue] and not just newValue.
Duplicate Keys Overwrite Each Other
If two pairs share a key, the later pair wins. This can happen without any warning when you swap keys and values.
const ratings = { alice: 5, bob: 3, carol: 5 };
const byRating = Object.fromEntries(
Object.entries(ratings).map(([name, rating]) => [rating, name])
);
console.log(byRating); // { '3': 'bob', '5': 'carol' }The pair for alice was overwritten by carol. The numeric keys also became strings, as all non-symbol keys do.
Other Sources of Pairs
Object.fromEntries accepts any iterable of pairs, so it works with more than arrays. Converting a Map to a plain object takes one call:
const counts = new Map([['red', 3], ['blue', 1]]);
console.log(Object.fromEntries(counts)); // { red: 3, blue: 1 }It also works with URLSearchParams, which turns a query string into an object:
const params = new URLSearchParams('page=2&sort=name');
console.log(Object.fromEntries(params)); // { page: '2', sort: 'name' }| Task | Array method | Callback returns |
|---|---|---|
| Change values | `map` | `[key, newValue]` |
| Remove properties | `filter` | `true` to keep the pair |
| Rename keys | `map` | `[newKey, value]` |
| Convert a Map | none | not needed |
Exercise
Given const stock = { apples: 4, pears: 0, plums: 7 }, write one expression that builds a new object containing only the items with a count above zero, with each count doubled.
Show answer
Object.fromEntries(Object.entries(stock).filter(([, count]) => count > 0).map(([item, count]) => [item, count * 2])) produces { apples: 8, plums: 14 }. Filtering first means the map callback only runs on the pairs you keep.
Exercise
Why does Object.fromEntries(Object.entries({ a: 1, b: 2 }).map(([k, v]) => v)) throw a TypeError?
Show answer
The map callback returns plain numbers, so Object.fromEntries receives [1, 2] where it expects [key, value] pairs. The callback must return a pair such as [k, v].