How to Merge the Properties of Two JavaScript Objects
Topic: JavaScript / jQueryPrev|Next
Answer: Use the Spread Operator (...
)
You can simply use spread operator (...
) to merge two or more objects into one in JavaScript.
Let's take a look at an example to understand how it basically works:
Example
Try this code »// Sample objects
var obj1 = { make: "Audi", model: "Q8" };
var obj2 = { color: "Blue", year: 2021 };
// Merging objects
var mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj);
// Prints: {make: "Audi", model: "Q8", color: "Blue", year: 2021}
Please note that properties of object that appear later in the list will overwrite the earlier ones if they have the same name or key. To better understand this, let's check out an example:
Example
Try this code »// Sample objects
var obj1 = { name: "John", age: 24 };
var obj2 = { name: "Alice", gender: "female" };
// Merging objects
var mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj);
// Prints: {name: "Alice", age: 24, gender: "female"}
As you can see above, the name
property in the obj1 is overwritten by the name property in the obj2.
Alternatively, you can use the Object.assign()
method to copy all properties from one or more source objects to a target object. Let's try out an example and see how it works:
Example
Try this code »// Sample objects
var target = { a: "Apple", b: "Ball" };
var source = { x: 1, y: 4 };
// Merging source object into target object
var returnedTarget = Object.assign(target, source);
console.log(returnedTarget);
// Prints: {a: "Apple", b: "Ball", x: 1, y: 4}
console.log(target);
// Prints: {a: "Apple", b: "Ball", x: 1, y: 4}
Please note that only the first object in the list of arguments will be modified and returned. Also, later properties will overwrite earlier properties if they have the same name.
See the tutorial on JavaScript Objects to learn more about creating and manipulating objects.
Related FAQ
Here are some more FAQ related to this topic: