const firstObject = { sampleData: 'Hello world' }
const secondObject = { moreData: 'foo bar' }
const finalObject = {
firstObject,
secondObject
};
const firstObject = { sampleData: 'Hello world' }
const secondObject = { moreData: 'foo bar' }
const finalObject = Object.assign({}, firstObject, secondObject);
const firstObject = { sampleData: 'Hello world' }
const secondObject = { moreData: 'foo bar' }
const finalObject = {}
for (let key in firstObject) {
finalObject[key] = firstObject[key];
}
for (let key in secondObject) {
finalObject[key] = secondObject[key];
}
const firstObject = { sampleData: 'Hello world' }
const secondObject = { moreData: 'foo bar' }
const finalObject = {}
for (let key in firstObject) {
if (Object.prototype.hasOwnProperty.call(firstObject, key)) {
finalObject[key] = firstObject[key];
}
}
for (let key in secondObject) {
if (Object.prototype.hasOwnProperty.call(secondObject, key)) {
finalObject[key] = secondObject[key];
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using the spread operator | |
Using Object.assign | |
Using For-In loop | |
Using For-In loop with hasOwnProperty |
Test name | Executions per second |
---|---|
Using the spread operator | 37821168.0 Ops/sec |
Using Object.assign | 28400752.0 Ops/sec |
Using For-In loop | 57670288.0 Ops/sec |
Using For-In loop with hasOwnProperty | 31112040.0 Ops/sec |
Let's break down what's being tested in this benchmark.
The test is designed to measure which method is the fastest for merging two objects without mutating them. The three methods being compared are:
...
): This syntax allows you to create a new object by spreading the properties of an existing object.Pros and Cons of each approach:
...
):The use of Object.prototype.hasOwnProperty.call()
in the For-In loop variant adds an extra layer of complexity, as it checks if the property belongs to the object itself (not inherited from a prototype), which can be beneficial for avoiding unintended property assignments.
Other considerations:
Object.assign()
with multiple sources or libraries like Lodash might be a better fit.Alternative approaches:
merge()
function: This is a popular and well-maintained library that provides a flexible way to merge objects, including support for nested objects, arrays, and more.merge()
function: Another widely used library that offers similar functionality to Lodash's merge()
, with some additional features like handling nested arrays.Object.entries()
, Array.prototype.forEach()
, and Object.fromEntries()
to create a custom merge function.Keep in mind that the choice of method ultimately depends on your specific use case, performance requirements, and personal preference.