Q:

How to Merge the Properties of Two JavaScript Objects

0

How to Merge the Properties of Two JavaScript Objects

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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:

// 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:

// 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:

// 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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Get the Length of a JavaScript Object... >>
<< How to Sort an Array of Objects by Property Values...