JavaScript objects have dynamic properties.
This means that we can merge the properties of 2 JavaScript objects dynamically.
This is an operation that’s done frequently.
In this article, we’ll look at how to merge properties of 2 JavaScript objects dynamically.
Spread Operator
The spread operator is available to objects since ES2018.
It lets us merge 2 objects’ properties together with ease.
For instance, we can write:
const obj1 = {
a: 1
}
const obj2 = {
b: 2
}
const merged = {
...obj1,
...obj2
};
The spread operator is the 3 dots.
It copies the p[roperies from obj1
and obj2
in the same order that they’re written.
Therefore, merged
is {a: 1, b: 2}
.
If 2 objects have the same properties, then the value of the last one that’s merged in overwrites the one that’s there previously.
For instance, if we have:
const obj1 = {
a: 1
}
const obj2 = {
a: 2
}
const merged = {
...obj1,
...obj2
};
Then merged
is {a: 2}
.
Object.assign
The Object.assign
method also lets us combine 2 objects together and return one merged object as the result.
For instance, we can write:
const obj1 = {
a: 1
}
const obj2 = {
b: 2
}
const merged = Object.assign(obj1, obj2);
Then merged
is {a: 1, b: 2}
.
The object in the first argument is mutation.
So if we want to return a new object with the properties of 2 objects without changing them, we pass in an empty array as the first argument:
const obj1 = {
a: 1
}
const obj2 = {
b: 2
}
const merged = Object.assign({}, obj1, obj2);
Object.assign
is available since ES6
for-in Loop
If the 2 ways above aren’t available, then we can use the for-in
loop as the last resort.
It’s definitely not recommended since the 2 options above have been available for a few years.
And they’re much simpler and easier to use.
But if we need to use the for-in
loop, we write:
const obj1 = {
a: 1
}
const obj2 = {
b: 2
}
const merged = {}
for (const prop in obj1) {
merged[prop] = obj1[prop];
}
for (const prop in obj2) {
merged[prop] = obj2[prop];
}
We loop through all the properties of obj1
and obj2
with the for-in
loop and put all the properties values into the merged
object.
prop
has the property name.
And so merged
is:
{a: 1, b: 2}
Conclusion
We can use the spread operator and Object.assign
to merge properties from different objects into one object.