<!--your preparation HTML code goes here-->
const record = {
jhon: {name: "jhon", lastname: "smith"},
doe: {name: "jhon", lastname: "doe"},
maria: {name: "maria", lastname: "lagg"},
}
const array = [];
for(const key in record){
const item = record[key];
array.push({firstName: item.name,lastName: item.lastname});
}
const array = Object.values(record).map(item => ({firstName: item.name,lastName: item.lastname}));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for-in push | |
Object.Values map |
Test name | Executions per second |
---|---|
for-in push | 20865522.0 Ops/sec |
Object.Values map | 20350020.0 Ops/sec |
The benchmark described in the provided JSON evaluates the performance of two approaches for transforming an object containing user records into an array of user objects. The object records contain names and last names of users.
for-in push:
const array = [];
for(const key in record) {
const item = record[key];
array.push({firstName: item.name, lastName: item.lastname});
}
for-in
loop to iterate over the keys of the record
object. For each key, it retrieves the corresponding item and pushes a new object containing the first and last names into the array
.for-in
loop enumerates all properties of the object, which may include inherited properties if prototypes are involved, leading to unintended results if not managed properly.Object.Values map:
const array = Object.values(record).map(item => ({firstName: item.name, lastName: item.lastname}));
Object.values()
to first extract an array of the object's values (the user records). It then uses the .map()
function to create a new array from these values by transforming each record into an object with the desired structure.Object.values()
method provides a direct way to obtain an array of values from the object, simplifying the iteration process.map()
function is a higher-order function that is generally well-optimized in modern JavaScript engines. It sidesteps the issues related to property enumeration that might occur with the for-in
loop.Object.values()
and map()
.The benchmark results indicate the following executions per second:
Overall, the for-in push
approach was more performant in this specific benchmark, but the Object.Values()
and map()
method is typically favored for its readability and functional programming style.
Other alternatives to consider for similar tasks could include:
Object.entries()
: This would allow direct access to both keys and values in an array format, which can also be used in conjunction with map()
, providing yet another way to transform the data.forEach()
method: Though less common for such transformations, using forEach()
over Object.values()
can create a similar result while offering clarity on iteration.In summary, when choosing an approach, developers should balance performance with code readability and maintainability, taking the context of the application into account.