JavaScript(JS) JS merge property of two objects
To merge the properties of two objects, you can use the Object.assign()
method or the object spread syntax (...
).
Here's an example using Object.assign()
:
const obj1 = { a: 1, b: 2 }; const obj2 = { c: 3, d: 4 }; const mergedObj = Object.assign({}, obj1, obj2); console.log(mergedObj); // Output: { a: 1, b: 2, c: 3, d: 4 }Sourcww:ew.theitroad.com
In the example above, we first define two objects obj1
and obj2
. We then create a new object mergedObj
by using Object.assign()
and passing in an empty object {}
as the target object, and the two objects obj1
and obj2
as the source objects to merge.
Here's an example using the object spread syntax:
const obj1 = { a: 1, b: 2 }; const obj2 = { c: 3, d: 4 }; const mergedObj = { ...obj1, ...obj2 }; console.log(mergedObj); // Output: { a: 1, b: 2, c: 3, d: 4 }
In the example above, we create a new object mergedObj
by using the object spread syntax and passing in the two objects obj1
and obj2
to merge.
Both Object.assign()
and the object spread syntax will create a new object with the merged properties of the two input objects. If there are any properties with the same name in both objects, the value of the property in the second object (obj2
in the examples above) will overwrite the value of the property in the first object (obj1
in the examples above).