Oftentimes, we may want to duplicate a JavaScript object’s properties into another object.
In this article, we’ll look at how to duplicate JavaScript object properties in another JavaScript object.
Using the Object.assign Method
One way to duplicate an object’s properties in another object is to use the Object.assign
method.
For instance, we can write:
const firstObject = {
a: 1,
b: 2
}
const secondObject = {
c: 3
}
Object.assign(secondObject, firstObject);
console.log(secondObject)
We have the firstObject
and secondObject
objects with some properties.
Then we call Object.assign
to copy the properties of the firstObject
object into the secondObject
.
Therefore, from the console log, we see that secondObject
is:
{c: 3, a: 1, b: 2}
after we call Object.assign
.
If we don’t want to modify secondObject
, we can write:
const firstObject = {
a: 1,
b: 2
}
const secondObject = {
c: 3
}
const thirdObject = Object.assign({}, firstObject, secondObject)
console.log(thirdObject)
Then thirdObject
is:
{a: 1, b: 2, c: 3}
and secondObject
is unmodified.
Spread Operator
Another way to copy an object’s property into another object is to use the spread operator.
For instance, we can write:
const firstObject = {
a: 1,
b: 2
}
const secondObject = {
c: 3
}
const thirdObject = {
...firstObject,
...secondObject
}
console.log(thirdObject)
We created a thirdObject
object which is created from spreading the properties of firstObject
and secondObject
into it.
Therefore, thirdObject
is:
{a: 1, b: 2, c: 3}
Conclusion
We can use the Object.assign
method or the spread operator to copy properties from one object onto another.