Sub topic 9
Building New Objects with Object.fromEntries
This chapter assumes you know Object.entries, array destructuring in arrow-function parameters, and the array methods map, filter, and reduce. The earlier chapters covered how to take an object apart into [key, value] pairs. This chapter goes the other way: it shows how to put pairs back together into a new object, and what can go wrong when you do.
The Missing Half of Object.entries
Object.entries turns an object into an array, so array methods can work on its properties. On its own, that only goes one way. After you filter or map the pairs, you still hold an array of pairs, not an object. Object.fromEntries (added in ES2019) turns that array back into an object.
const pairs = [['host', 'localhost'], ['port', 8080]];
const config = Object.fromEntries(pairs);
console.log(config); // { host: 'localhost', port: 8080 }
console.log(config.port); // 8080For any plain object with ordinary string keys, the two functions undo each other:
const original = { a: 1, b: 2 };
const copy = Object.fromEntries(Object.entries(original));
console.log(copy); // { a: 1, b: 2 }
console.log(copy === original); // falsecopy is a new object with the same keys and values. Later sections cover where this round trip loses information.
The Entries Pipeline
Most uses of Object.fromEntries follow one pattern. You split the object into pairs, change the pairs with array methods, and rebuild the object.
The source object is never modified. Every step returns a new array, and the last step returns a new object. That makes the pipeline safe for state you should not mutate, such as React props or a shared config object.
Transforming values
The most common job is applying a function to every value and keeping the keys:
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 }The callback for map must return a two-element array. Destructuring in the parameter list names the parts going in, and the array literal [fruit, price * 0.5] builds the pair coming out.
If you do this often, wrap it in a helper:
function mapValues(obj, fn) {
return Object.fromEntries(
Object.entries(obj).map(([key, value]) => [key, fn(value, key)])
);
}
const stock = { apple: 3, pear: 0, plum: 12 };
console.log(mapValues(stock, (n) => n > 0)); // { apple: true, pear: false, plum: true }
console.log(mapValues(stock, (n, key) => `${key}:${n}`));
// { apple: 'apple:3', pear: 'pear:0', plum: 'plum:12' }Transforming keys
You can change the key half of each pair in the same way. This example converts snake_case keys from an API response into camelCase:
const toCamel = (s) => s.replace(/_([a-z])/g, (_, ch) => ch.toUpperCase());
const row = { user_id: 7, first_name: 'Ada', is_admin: false };
const user = Object.fromEntries(
Object.entries(row).map(([key, value]) => [toCamel(key), value])
);
console.log(user); // { userId: 7, firstName: 'Ada', isAdmin: false }Picking and omitting keys
filter decides which pairs make it into the new object. That gives you short pick and omit helpers:
function pick(obj, keys) {
return Object.fromEntries(
Object.entries(obj).filter(([key]) => keys.includes(key))
);
}
function omit(obj, keys) {
return Object.fromEntries(
Object.entries(obj).filter(([key]) => !keys.includes(key))
);
}
const account = { id: 1, email: '[email protected]', password: 'hunter2' };
console.log(pick(account, ['id', 'email'])); // { id: 1, email: '[email protected]' }
console.log(omit(account, ['password'])); // { id: 1, email: '[email protected]' }You can also filter on values. This removes every null or undefined property without touching the original:
const settings = { theme: 'dark', font: null, size: 14, color: undefined };
const cleaned = Object.fromEntries(
Object.entries(settings).filter(([, value]) => value != null)
);
console.log(cleaned); // { theme: 'dark', size: 14 }
console.log(settings); // { theme: 'dark', font: null, size: 14, color: undefined }Why Not Just Use reduce?
Before Object.fromEntries existed, people rebuilt objects with reduce:
const prices = { apple: 1.2, pear: 0.8, plum: 2 };
const discounted = Object.entries(prices).reduce((acc, [fruit, price]) => {
acc[fruit] = price * 0.5;
return acc;
}, {});
console.log(discounted); // { apple: 0.6, pear: 0.4, plum: 1 }This works, and it is still a fair choice when one pass has to filter, rename, and compute at once. But it has known pitfalls:
- Forgetting
return accgivesundefinedon the next step and a confusingTypeError. - The tempting one-liner
(acc, [k, v]) => ({ ...acc, [k]: v })copies the whole accumulator on every step. That is quadratic time and gets slow on large objects. - The intent ("build an object from pairs") is hidden inside the callback.
| Approach | Readability | Performance | Best for |
|---|---|---|---|
| `entries` + `map` + `fromEntries` | Clear, declarative | Linear | Reshaping keys or values |
| `entries` + `filter` + `fromEntries` | Clear, declarative | Linear | Picking or omitting properties |
| `reduce` mutating `acc` | Moderate | Linear | Complex single-pass logic |
| `reduce` spreading `acc` | Looks neat | Quadratic | Avoid for anything but tiny objects |
Any Iterable of Pairs Works
Object.fromEntries does not require an array. It accepts any iterable (anything for...of can loop over) whose items are pair-like. That makes it the standard way to convert a Map or URLSearchParams into a plain object.
const counts = new Map([
['red', 3],
['blue', 5],
]);
console.log(Object.fromEntries(counts)); // { red: 3, blue: 5 }
const params = new URLSearchParams('page=2&sort=name');
console.log(Object.fromEntries(params)); // { page: '2', sort: 'name' }Generators work too, which lets you build objects lazily without an intermediate array:
function* squares(n) {
for (let i = 1; i <= n; i++) {
yield [`n${i}`, i * i];
}
}
console.log(Object.fromEntries(squares(3))); // { n1: 1, n2: 4, n3: 9 }Edge Cases and Failure Modes
Duplicate keys: last one wins
Each pair is assigned in order, so a later pair with the same key overwrites an earlier one. You get no error and no warning.
console.log(Object.fromEntries([['a', 1], ['b', 2], ['a', 3]])); // { a: 3, b: 2 }
const query = new URLSearchParams('tag=js&tag=web');
console.log(Object.fromEntries(query)); // { tag: 'web' }
console.log(query.getAll('tag')); // [ 'js', 'web' ]Key renaming can cause the same collision. If two source keys map to the same new key, one value disappears.
Keys are coerced to strings
Object keys must be strings or symbols, so other key types get converted. Numbers are mostly harmless. Objects used as keys become '[object Object]', which loses data:
const m = new Map([
[1, 'one'],
[true, 'yes'],
[{ id: 1 }, 'first'],
[{ id: 2 }, 'second'],
]);
console.log(Object.fromEntries(m));
// { '1': 'one', true: 'yes', '[object Object]': 'second' }The Map held four entries, but the object has three. Symbol keys are kept as symbols, because they are valid property keys.
The same coercion applies when you swap keys and values. Every former value becomes a string key, and duplicate values collapse:
const codes = { ok: 200, created: 201, fine: 200 };
const byCode = Object.fromEntries(
Object.entries(codes).map(([name, code]) => [code, name])
);
console.log(byCode); // { '200': 'fine', '201': 'created' }The output also shows that integer-like keys follow the ordering rules from the previous chapter. The new object lists them in ascending numeric order, whatever order the pairs arrived in.
Malformed entries
Each item must be an object. Object.fromEntries reads its 0 property as the key and its 1 property as the value. Missing positions become undefined, extra positions are ignored, and primitives throw:
console.log(Object.fromEntries([['a']])); // { a: undefined }
console.log(Object.fromEntries([['b', 2, 'x']])); // { b: 2 }
try {
Object.fromEntries([['ok', 1], 'ab']);
} catch (err) {
console.log(err instanceof TypeError); // true
}
try {
Object.fromEntries({ a: 1 });
} catch (err) {
console.log(err instanceof TypeError); // true: a plain object is not iterable
}The last case is a common mistake. Passing an object directly instead of its entries throws, because plain objects are not iterable.
What the round trip loses
Object.fromEntries(Object.entries(obj)) copies only what Object.entries returns, and it always produces a plain object. Several things are lost on the way:
class Point {
constructor(x, y) { this.x = x; this.y = y; }
get length() { return Math.hypot(this.x, this.y); }
}
const p = new Point(3, 4);
const copy = Object.fromEntries(Object.entries(p));
console.log(copy); // { x: 3, y: 4 }
console.log(copy instanceof Point); // false
console.log(copy.length); // undefined
const nested = { meta: { tags: ['a'] } };
const shallow = Object.fromEntries(Object.entries(nested));
shallow.meta.tags.push('b');
console.log(nested.meta.tags); // [ 'a', 'b' ]- Prototype: the result is a plain object, so class methods and inherited getters are gone.
- Getters: own getters are called once, and the copy stores the value they returned at that moment.
- Hidden keys: symbol keys and non-enumerable properties are skipped, because
Object.entriesskips them. - Depth: the copy is shallow. Nested objects and arrays are shared with the original.
When you need a deep copy, use structuredClone. When you need to keep symbols or property descriptors, build the object from Reflect.ownKeys and Object.getOwnPropertyDescriptors instead.
Exercises
Exercise
Write a function invertUnique(obj) that swaps keys and values using Object.entries and Object.fromEntries, but throws an Error if two keys share the same value. What does invertUnique({ a: 'x', b: 'y' }) return?
Show answer
One solution: function invertUnique(obj) { const pairs = Object.entries(obj).map(([k, v]) => [v, k]); const result = Object.fromEntries(pairs); if (Object.keys(result).length !== pairs.length) { throw new Error('Duplicate values'); } return result; } Comparing the key count with the pair count detects collisions, because duplicate keys overwrite each other inside fromEntries. invertUnique({ a: 'x', b: 'y' }) returns { x: 'a', y: 'b' }.
Exercise
What does this log, and why? const m = new Map([[2, 'b'], ['z', 'last'], [1, 'a'], ['z', 'again']]); console.log(Object.fromEntries(m));
Show answer
It logs { '1': 'a', '2': 'b', z: 'again' }. A Map overwrites a repeated key in place, so 'z' keeps its first position but holds 'again'. Object.fromEntries then converts the numeric keys to the strings '1' and '2', and the object lists integer-like keys first in ascending order, followed by z.
Exercise
A teammate writes Object.fromEntries(user) to make a copy of a plain object user and gets a TypeError. Explain the error and give two ways to fix it, saying which is better for a shallow copy.
Show answer
Object.fromEntries expects an iterable of pairs, and plain objects are not iterable, so it throws. One fix is Object.fromEntries(Object.entries(user)). The other is the spread syntax { ...user }. For an unchanged shallow copy, { ...user } is simpler and clearer. Use the entries pipeline only when you also need to filter or transform the pairs.