var array = Array.from(Array(10000).keys()).map((i) => ({
id: i,
count: i * 100,
}))
Object.fromEntries(array.map(({ id, count }) => [id, count]));
array.reduce((obj, { id, count }) => {
obj[id] = count;
return obj;
}, {});
array.reduce((obj, { id, count }) => Object.assign(obj, { [id]: count }), {});
array.reduce((obj, { id, count }) => ({ obj, [id]: count }), {});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.fromEntries(array.map) | |
Array.reduce (reuse same object) | |
Array.reduce (use Object.assign) | |
Array.reduce (use destructuring) |
Test name | Executions per second |
---|---|
Object.fromEntries(array.map) | 2415.2 Ops/sec |
Array.reduce (reuse same object) | 17950.7 Ops/sec |
Array.reduce (use Object.assign) | 238.3 Ops/sec |
Array.reduce (use destructuring) | 115.4 Ops/sec |
Let's break down the benchmark and its options.
Benchmark Definition
The benchmark tests four different approaches for reducing an array to a single object:
Object.fromEntries(array.map(({ id, count }) => [id, count]));
array.reduce((obj, { id, count }) => {\r\n obj[id] = count;\r\n return obj;\r\n}, {});
array.reduce((obj, { id, count }) => Object.assign(obj, { [id]: count }), {});
array.reduce((obj, { id, count }) => ({ ...obj, [id]: count }), {});
These approaches are used to create an object from the array's elements, where each element is mapped to a key-value pair.
Options Comparison
Let's examine each option:
Object.fromEntries(array.map(({ id, count }) => [id, count]));
: This approach uses the fromEntries
method, which creates an object from an array of key-value pairs.array.reduce((obj, { id, count }) => {\r\n obj[id] = count;\r\n return obj;\r\n}, {});
: This approach uses the reduce
method, which applies a callback function to each element in the array and accumulates the results.array.reduce((obj, { id, count }) => Object.assign(obj, { [id]: count }), {});
: This approach uses Object.assign
, which copies properties from one or more source objects into a target object.array.reduce((obj, { id, count }) => ({ ...obj, [id]: count }), {});
: This approach uses the spread operator ({ ...obj, [id]: count }
) to create a new object with updated properties.Library
None of the approaches use a specific JavaScript library. However, Object.fromEntries
is a relatively recent addition to the ECMAScript standard (ES2020), while Object.assign
has been part of the standard since ES5.
Special JS Features or Syntax
The benchmark uses the following special features or syntax:
{ ...obj, [id]: count }
) in option 4.() => { obj[id] = count; return obj; }
) in options 2 and 3.\r\n obj[id] = count;\r\n return obj;\r\n}
) in options 2 and 3.Other Alternatives
For reducing an array to a single object, other alternatives include:
reduce
method with a callback function that returns an updated object.map
method followed by the reduce
method.Keep in mind that the best approach will depend on the specific use case and performance requirements.