How to Combine Two Objects in JavaScript

JavaScript, a key pillar of modern web development, offers countless possibilities to programmers. Understanding its intricacies can empower us to create dynamic, interactive websites. One such intriguing aspect of JavaScript is the ability to combine two objects.

Have you ever wondered how to merge two objects in JavaScript into one, and when such a practice can be helpful? Combining objects can be a clever solution when dealing with a set of related data spread across multiple objects. Get ready to dive deep into this fascinating feature.

In this post, we will be looking at the following 3 ways to combine two objects in JavaScript:

  • By using Object.assign() method
  • By using the spread operator {…}
  • By using jQuery’s $.extend() method

Let’s explore each…

#1 – By using Object.assign() method

By using Object.assign() method

In JavaScript, the Object.assign() method is used to combine two or more objects, copying the values of all enumerable own properties from the source objects to a target object, which it then returns. This method alters the target object and can be better understood through an example.


let obj1 = { a: 1, b: 2 };
let obj2 = { b: 3, c: 4 };

let combinedObj = Object.assign(obj1, obj2);

console.log(combinedObj); // Output: { a: 1, b: 3, c: 4 }

How it works

The Object.assign() method takes the target object as its first argument and one or more source objects as its subsequent arguments. It then iterates over the source objects from left to right, copying their properties to the target object. If there are any conflicts (i.e., properties that exist in the target and also in the current source object), the value from the source object overwrites the one in the target.

Here’s a step-by-step breakdown of how the code example above works:

  • The Object.assign() method is called with obj1 as the target object and obj2 as the source object.
  • It starts by copying the properties of obj1 (i.e., a and b) to the new object combinedObj.
  • Then it moves on to obj2 and copies its properties to combinedObj. The property b already exists in combinedObj, so the value from obj2 (i.e., 3) overwrites the existing value in combinedObj (i.e., 2). The property c doesn’t exist in combinedObj, so it’s simply added.
  • Finally, Object.assign() returns combinedObj, which now has the combined properties of obj1 and obj2.

It’s important to note that Object.assign() does not create a deep clone of the source objects. If a source object’s property is a reference to another object, that reference is copied to the target object, not the actual object it refers to.

#2 – By using the spread operator {…}

By using the spread operator {...}

The spread operator {…} in JavaScript allows you to merge properties of two or more objects into a new one. This can be better understood with a practical example below:


let obj1 = { a: 1, b: 2 };
let obj2 = { b: 3, c: 4 };

let combinedObj = { ...obj1, ...obj2 };

How it works

The spread operator, represented by … , is used to unpack elements from objects into individual elements. In the context of combining objects, it essentially extracts the key-value pairs from each object and merges them into a new one. If there are duplicate keys, the value from the last mentioned object will overwrite previous values.

  • The variables obj1 and obj2 are initialized with their respective key-value pairs. Obj1 has keys ‘a’ and ‘b’ with values 1 and 2, and obj2 has keys ‘b’ and ‘c’ with values 3 and 4.
  • The spread operator … is used to unpack the properties of obj1 and obj2 into a new object named combinedObj.
  • In the resulting combinedObj, if there are any matching keys in both obj1 and obj2, the value from the latter object (obj2) will overwrite the value from the former object (obj1).
  • Thus, in combinedObj, the key ‘b’ has the value 3 (from obj2) instead of 2 (from obj1), and all other key-value pairs are included as is.
  • So, combinedObj is { a: 1, b: 3, c: 4 }.

#3 – By using jQuery’s $.extend() method

By using jQuery's $.extend() method

The $.extend() method in jQuery is used for merging the contents of two or more objects into the first object. It’s similar to how taking different ingredients and combining them forms a new recipe. Let’s explore this with an example.


 var object1 = {
 apple: 0,
 banana: { weight: 52, price: 100 },
 cherry: 97
 };
 
 var object2 = {
 banana: { price: 200 },
 durian: 100
 };
 
 $.extend( object1, object2 );

How it works

The $.extend() function takes an unlimited number of objects as arguments. It starts merging from left to right, meaning the properties of the objects further to the right will overwrite the properties of the objects to their left if they share the same keys.

  • First, we have defined two objects: ‘object1’ and ‘object2’. Each object has different key-value pairs. ‘object1’ has keys ‘apple’, ‘banana’, and ‘cherry’, while ‘object2’ has keys ‘banana’ and ‘durian’.
  • Next, we call the $.extend() function with ‘object1’ and ‘object2’ as parameters. Here, ‘object1’ is the target object that will be modified to incorporate the properties of ‘object2’.
  • The ‘banana’ key in both objects leads to an interesting case: this key’s value is another object. As the $.extend() function performs a shallow copy, the ‘banana’ object from ‘object2’ will completely overwrite the ‘banana’ object in ‘object1’.
  • Finally, any properties in ‘object2’ that aren’t in ‘object1’ (in this case, ‘durian’) are simply added to ‘object1’.

After calling the $.extend() function, ‘object1’ will be:


 {
 apple: 0,
 banana: { price: 200 },
 cherry: 97,
 durian: 100
 }

‘object2’ will remain unaffected.

Related:

In conclusion, merging objects in JavaScript is a powerful way to manipulate and manage data within your applications. We’ve seen that methods such as the Spread operator and Object.assign() can make this process efficient and straightforward.

Remember, while combining objects, it’s important to consider factors like order of properties and handling of duplicate keys. With a little practice, you’ll soon be mastering these techniques to level up your JavaScript development skills.

Leave a Reply

Your email address will not be published. Required fields are marked *