var data = Array.from(Array(10000).keys()).map(i => ({id: i, value: `val_${i}`}));
Object.fromEntries(data.map(obj => [obj.id, obj]));
data.reduce((acc, obj) => {
acc[obj.id] = obj;
return acc;
}, {});
data.reduce((acc, obj) => ({
acc,
[obj.id]: obj
}), {});
--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 | 2946.0 Ops/sec |
Reduce (reuse object) | 4878.4 Ops/sec |
Reduce (creating temporary objects) | 36.9 Ops/sec |
The provided JSON represents a JavaScript benchmark test case for the "Convert Array to Object" microbenchmark. The benchmark aims to measure the performance of two approaches:
Object.fromEntries: This method creates a new object from an array of key-value pairs. It's a relatively modern method introduced in ECMAScript 2015 (ES6).
Reduce:
reduce
method to create a new object, and for each iteration, it checks if the property already exists in the accumulator (acc
). If it does, it overwrites the existing value. Then, it adds the new key-value pair to the object.reduce
method but creates temporary objects instead of reusing an existing one.Options Compared:
Pros and Cons:
Object.fromEntries:
Reuse Object (Reduce):
Creating Temporary Objects (Reduce):
Library:
Array.from()
method is used which comes from the built-in JavaScript array methods.Special JS Feature or Syntax:
To better understand these alternatives, consider the following scenarios:
Ultimately, the best approach depends on your specific use case and requirements. The performance differences between these methods may be small for small arrays but become more pronounced with larger datasets.
Other Alternatives:
fromPairs
method: This is another popular method used to convert an array of key-value pairs into a new object. It shares similarities with Object.fromEntries and can be useful if you prefer a specific syntax or behavior....object
): For simple cases, this approach can be as efficient as Object.fromEntries but might not work as well for more complex scenarios where properties need to be overwritten.Before deciding on any method, consider factors like performance, readability, and maintainability based on your specific requirements.