Union of Two Objects in JavaScript



In this article, we will learn to calculate the union of two objects in JavaScript. The union of two objects results in a new object that contains all the properties of both objects.

What is the Union of Two Objects?

The union of two objects is the process of combining the properties of both objects into a single object.

For example

Input ?

const obj1 = { name: " ", email: " " };
const obj2 = { name: ['x'], email: ['y']};

Output ?

const output = { name: {" ", [x]}, email: {" ", [y]} };

Different Approaches

The following are the two different approaches to calculate the union of two objects in Java ?

Using Loop

In this approach, we will be iterating through the for loop for both objects and adds their values to a new object using the concat() method ensuring all values are merged into arrays.

Following are the steps to calculate the union of two objects using loops ?

  • Create an empty object: It has predefined keys with empty arrays to store merged values.
  • Loop through obj1: Uses concat() method to ensure values from obj1 are added to arrays in obj3.
  • Loop through obj2: Also uses concat() to combine values.
  • Return the merged object: The final result ensures both obj1 and obj2 values are stored in arrays.

Initialize object obj3 with empty arrays for name & email ?

const obj3 = { name: [], email: [] };

 Append obj1 values to obj3[key]using contact() method ?

obj3[key] = obj3[key].concat(obj1[key]);

Example

Below is an example of calculating the union of two objects using loops ?

const obj1 = { name: " ", email: " " };
const obj2 = { name: ['x'], email: ['y'] };

const objectUnion = (obj1 = {}, obj2 = {}) => {
   const obj3 = { name: [], email: [] };
   for (let key in obj1) {  
      obj3[key] = obj3[key].concat(obj1[key]);
   }
   for (let key in obj2) {  
      obj3[key] = obj3[key].concat(obj2[key]);
   }
   return obj3;
};

console.log(objectUnion(obj1, obj2));

Output

{ name: [ ' ', [ 'x' ] ], email: [ ' ', [ 'y' ] ] }

Time Complexity: O(n), iterates through both objects once.
Space Complexity: O(n), creates a new object storing all values.  

Using reduce()

In this approach, we will use the reduce() method to dynamically merge multiple objects into a single object by iterating over their keys and using concat() to accumulate values.

Following are the steps to calculate the union of two objects using reduce() ?

  • Use reduce() to iterate over all objects (obj1, obj2, etc.): Starts with an empty object {}.
  • Loop through each object's keys (name, email, etc.): for (let key in obj) {...} dynamically accesses properties.
  • Dynamically merge values: (acc[key] || []) ensures that acc[key] is an array, even if it doesn't exist yet, the concat(obj[key]) adds new values without modifying the original structure.
  • Return the final merged object: Works for any object structure, not just predefined keys.

Iterate over objects obj1 and obj2 using reduce() method ?

return objects.reduce((acc, obj) => { }

Merge value dynamically using for loop and concat() method ?

for (let key in obj) {  
         acc[key] = (acc[key] || []).concat(obj[key]);
      }

Example

Below is an example of calculating the union of two objects using reduce() ?

const obj1 = { name: " ", email: " " };
const obj2 = { name: ['x'], email: ['y'] };

const objectUnionReduce = (...objects) => {
   return objects.reduce((acc, obj) => {
      for (let key in obj) {  
         acc[key] = (acc[key] || []).concat(obj[key]);
      }
      return acc;  
   }, {});
};

console.log(objectUnionReduce(obj1, obj2));

Output

{ name: [ ' ', [ 'x' ] ], email: [ ' ', [ 'y' ] ] }

Time Complexity: O(n), processes all objects and their keys once.
Space Complexity: O(n), stores merged results in a new object.

Conclusion

A frequent operation in JavaScript can calculate the union of two objects, which may be done using any of several ways from an iteration to the reduce() function. The straightforward iteration-based approach, however, is best suited for just predefined keys, while the reduce() method is more dynamic when multiple or unknown key structures are used to add or merge objects.

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-02-26T19:36:58+05:30

446 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements