How do I merge two objects in JavaScript?
Davide S
davide s profile pic

To merge two objects in JavaScript, you can use various approaches, such as the spread operator,Object.assign(), or a custom merge function. Here are examples of each approach: 1. Using the spread operator:

1
2
3
4
5

   function mergeObjects(obj1, obj2) {
     return { ...obj1, ...obj2 };
   }
   

In this example, themergeObjects function takesobj1 andobj2 as parameters. The spread operator (...) is used to create a new object by merging the properties of both objects. If there are properties with the same name, the value fromobj2 will overwrite the value fromobj1. 2. UsingObject.assign():

1
2
3
4
5

   function mergeObjects(obj1, obj2) {
     return Object.assign({}, obj1, obj2);
   }
   

TheObject.assign() method is used to merge the properties of two or more objects into a target object. In this case, an empty object ({}) is used as the target object, andobj1 andobj2 are merged into it. Similarly, properties fromobj2 will overwrite properties fromobj1 if they have the same name. 3. Using a custom merge function:

1
2
3
4
5
6
7
8
9
10
11
12

   function mergeObjects(obj1, obj2) {
     const merged = {};
     for (let key in obj1) {
       merged[key] = obj1[key];
     }
     for (let key in obj2) {
       merged[key] = obj2[key];
     }
     return merged;
   }
   

This approach manually iterates over the properties of both objects usingfor...in loops and assigns each property to a new object (merged). The resulting object contains all properties from bothobj1 andobj2. Here's an example usage of themergeObjects function:

1
2
3
4
5
6

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

const merged = mergeObjects(obj1, obj2);
console.log(merged); // Output: { a: 1, b: 3, c: 4 }

In this example,obj1 andobj2 have overlapping properties (b). The resultingmerged object contains all properties from both objects, with the value fromobj2 overwriting the value fromobj1 for theb property. Choose the approach that suits your needs based on factors such as simplicity, compatibility, or specific requirements. Additionally, consider edge cases, such as handling nested objects or arrays, and adapt the merge function accordingly if needed.