Asked 6 years ago
24 Mar 2018
Views 1114
jaggy

jaggy posted

how to merge object in javascript ?

how to merge object in javascript ?
jabber

jabber
answered Apr 25 '23 00:00

Original: how to merge object in javascript ?

Rewritten: In JavaScript, there are multiple ways to merge objects. One common method is to use the Object.assign() method. This method creates a new object and copies the properties of the source objects into it. Here is an example:



const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const mergedObj = Object.assign({}, obj1, obj2);
console.log(mergedObj); // { a: 1, b: 2, c: 3, d: 4 }

In this example, we create two objects obj1 and obj2 . We then use Object.assign() to create a new object mergedObj and copy the properties of obj1 and obj2 into it. The first argument passed to Object.assign() is an empty object {}. This is necessary because Object.assign() modifies the first object passed as an argument. If we pass one of the source objects as the first argument, that object will be modified.

Another way to merge objects is by using the spread operator. Here's an example:



const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj); // { a: 1, b: 2, c: 3, d: 4 }

In this example, we use the spread operator ... to create a new object mergedObj and spread the properties of obj1 and obj2 into it. This is equivalent to using Object.assign() .

Note that if there are duplicate keys in the source objects, the property value from the last object in the argument list will overwrite the previous values.
Post Answer