var data = Array.from(Array(10000).keys()).map(v => ({id: v.toString(), value: `val=${v}`}));
Object.fromEntries(data.map(({id, value}) => [id, value]));
data.reduce((acc, {id, value}) => {
acc[id] = value;
return acc;
}, {});
data.reduce((acc, {id, value}) => ({
acc,
[id]: value
}), {});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.fromEntries | |
Reduce (reuse object) | |
Reduce (creating temporary objects) |
Test name | Executions per second |
---|---|
Object.fromEntries | 4581.0 Ops/sec |
Reduce (reuse object) | 7560.6 Ops/sec |
Reduce (creating temporary objects) | 52.2 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Purpose: The benchmark compares three approaches to convert an array of objects to a single object in JavaScript:
Object.fromEntries
with a mapped array of key-value pairs.Array.prototype.reduce()
with an initial empty object, where each iteration adds a new property to the object.Array.prototype.reduce()
with an initial empty object, but creating a temporary object on each iteration.Options Compared:
Pros and Cons:
Library/Libraries Used: None mentioned in the provided benchmark definition.
Special JavaScript Features/Syntax: The benchmark uses modern JavaScript features:
data
array creation string ("val=${v}"
).({ id, value }) => { ... }
).Other Alternatives:
{ ...array.map(item => item.id).map(id => ({ id })) }
) or the Array.prototype.forEach()
method.Array.prototype.reduce()
, but without reusing an object (as in the "Reuse object" variant).Keep in mind that these alternatives might have different performance characteristics and use cases compared to the benchmark's approaches.
In summary, this benchmark helps developers understand the trade-offs between different methods for converting arrays of objects to single objects in JavaScript, highlighting the pros and cons of each approach.