In the first code, you're creating a new object for every iteration of .reduce
. In certain engines, this may be slightly less efficient than your second code, which only creates a single object. (That said, efficiency rarely matters much; code clarity is much more important in most situations).
But, for this situation, there's an even more suitable method to use when creating an object from an array, which avoids the slightly clunky syntax of reduce
:
const output = Object.fromEntries(
items.map(item => [item.id, item])
);
const items = [
{ id: 5, val: 5 },
{ id: 10, val: 10 },
{ id: 15, val: 15 },
];
const output = Object.fromEntries(
items.map(item => [item.id, item])
);
console.log(output);
That said, keep in mind that Object.fromEntries
is a relatively new feature, so if this is meant for a public-facing website, make sure to include a polyfill.
new Map(items.map(x => [x.id, x.name]))
– Tuneless