Skip to content

objectEntriesMethods

Prefer Object.fromEntries() over reduce patterns that build objects from key-value pairs.

✅ This rule is included in the ts stylistic presets.

Object.fromEntries() is a built-in method that transforms a list of key-value pairs into an object. It provides a more readable and concise alternative to using reduce() to build objects from entries.

Using Object.fromEntries() with map() is clearer than the equivalent reduce pattern, and avoids creating unnecessary intermediate objects on each iteration.

const entries = [
["first", 1],
["second", 2],
];
const result = entries.reduce(
(accumulator, [key, value]) => ({ ...accumulator, [key]: value }),
{},
);
const entries = [
["first", 1],
["second", 2],
];
const result = entries.reduce(
(accumulator, [key, value]) => Object.assign(accumulator, { [key]: value }),
{},
);
const items = [
{ id: "a", name: "Alpha" },
{ id: "b", name: "Beta" },
];
const lookup = items.reduce(
(accumulator, item) => ({ ...accumulator, [item.id]: item.name }),
{},
);
const entries = Object.entries({ first: 1, second: 2 });
const doubled = entries.reduce(
(accumulator, [key, value]) => ({ ...accumulator, [key]: value * 2 }),
{},
);

This rule is not configurable.

If you need to support JavaScript environments that don’t have Object.fromEntries() (pre-ES2019), you might need to disable this rule or use a polyfill. Object.fromEntries() is supported in Node.js 12.0.0+ and all modern browsers.

Some reduce patterns are more complex than what this rule detects, such as when the accumulator needs additional processing or when building an object with conditional keys. If you use those patterns often and prefer to keep stylistic consistency with them, you might prefer to disable this rule.

Made with ❤️‍🔥 in Boston by Josh Goldberg and contributors.