Merging two objects in JavaScript is easy using the Object.assign()
method. This method allows you to copy the values of all enumerable properties from one or more source objects to a target object.
Object.assign(target, ...sources)
By merging two or more objects, you can create a new object that contains all the properties and values of the source objects.
JavaScript merges two objects example
Simple example code.
const obj1 = { name: "John", age: 30 };
const obj2 = { occupation: "Developer", city: "New York" };
const mergedObj = Object.assign({}, obj1, obj2);
console.log(mergedObj);
Output:
You can also merge objects using the spread operator ...
in JavaScript. Here’s an example:
const obj1 = { name: "John", age: 30 };
const obj2 = { occupation: "Developer", city: "New York" };
const mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj);
In summary, both the spread operator and Object.assign()
method are useful for merging objects in JavaScript, and the choice between them depends on the specific requirements of your use case. For simple merging scenarios, the spread operator is a good choice, whereas for more complex merging scenarios or when you need more control over the merging process, Object.assign()
method might be a better choice.
Comment if you have any doubts or suggestions on this JS Object topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version