const arr = [{ a: 1, b: 2 }, { a: 3, b: 4 }]
const res = arr.map(o => [o.a, o.b])
console.log(res);
const arr = [{ a: 1, b: 2 }, { a: 3, b: 4 }]
const res = arr.map(({ a, b }) => [a, b])
console.log(res);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Assign | |
Destructure |
Test name | Executions per second |
---|---|
Assign | 343260.1 Ops/sec |
Destructure | 342419.0 Ops/sec |
The benchmark titled "Assignment of value vs Destructuring an objectzz" compares two different JavaScript techniques for extracting values from objects in an array: direct assignment versus destructuring.
Test Case: Assign
const arr = [{ a: 1, b: 2 }, { a: 3, b: 4 }];
const res = arr.map(o => [o.a, o.b]);
console.log(res);
a
and b
. The map
function iterates over the array, and for each object (o
), it constructs an array containing the values of a
and b
. This approach uses standard object property access (dot notation).Test Case: Destructure
const arr = [{ a: 1, b: 2 }, { a: 3, b: 4 }];
const res = arr.map(({ a, b }) => [a, b]);
console.log(res);
map
function., which allows for direct extraction of the values of a
and b
from each object without needing to reference the object itself.Direct Assignment (Assign)
Destructuring (Destructure)
Based on the benchmark results:
Both methods are nearly equivalent in performance, with direct assignment being slightly faster in this test case.
Performance: Although the difference in performance is minimal, it's crucial to take into account the specific context in which the code will run. For instance, destructuring might be preferred for readability and maintainability, especially in larger codebases.
Code Readability and Team Standards: The choice between these methods can depend on code style guidelines adopted by a team, balancing brevity and clarity.
Other alternatives for similar operations could include:
Using a loop: Instead of using the map
method, a traditional for
loop could be written to manually create a new array, which might be more explicit but also more verbose and harder to read.
Using Object.entries() with a custom reduction: For operations that require more complex transformations, leveraging Object.entries()
with reduce
could allow for a wider range of manipulation of the objects.
In summary, both direct assignment and destructuring are valid approaches for accessing object properties in an array, each with its strengths and weaknesses. The decision on which to use may depend on performance considerations, code clarity, and team conventions.