JavaScript union of two objects

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. When properties have the same key, their values are merged together.

For example

Input ?

const obj1 = { name: "John", email: "john@email.com" };
const obj2 = { name: "Jane", email: "jane@email.com" };

Output ?

{ name: ["John", "Jane"], email: ["john@email.com", "jane@email.com"] }

Different Approaches

The following are two different approaches to calculate the union of two objects in JavaScript:

Using for...in Loop

In this approach, we iterate through both objects using for...in loop and merge their values into arrays using the concat() method.

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

  • Initialize an empty result object: Create an object to store merged values
  • Iterate through first object: Add all properties to the result object
  • Iterate through second object: Merge values with existing properties or add new ones
  • Return the merged object: Contains all properties from both objects

Example

Below is an example of calculating the union of two objects using for...in loop:

const obj1 = { name: "Alice", email: "alice@email.com", age: 25 };
const obj2 = { name: "Bob", city: "New York", age: 30 };

const objectUnion = (obj1, obj2) => {
    const result = {};
    
    // Add properties from first object
    for (let key in obj1) {
        result[key] = Array.isArray(obj1[key]) ? obj1[key] : [obj1[key]];
    }
    
    // Merge properties from second object
    for (let key in obj2) {
        if (result[key]) {
            // Merge with existing property
            result[key] = result[key].concat(obj2[key]);
        } else {
            // Add new property
            result[key] = Array.isArray(obj2[key]) ? obj2[key] : [obj2[key]];
        }
    }
    
    return result;
};

console.log(objectUnion(obj1, obj2));
{
  name: [ 'Alice', 'Bob' ],
  email: [ 'alice@email.com' ],
  age: [ 25, 30 ],
  city: [ 'New York' ]
}

Time Complexity: O(n + m), where n and m are the number of properties in obj1 and obj2.
Space Complexity: O(n + m), creates a new object storing all merged values.

Using reduce() Method

In this approach, we 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 using reduce():

  • Use reduce() to iterate over all objects: Starts with an empty accumulator object
  • Loop through each object's properties: Uses for...in to access all keys dynamically
  • Merge values dynamically: Combines values using concat() method
  • Return the final merged object: Works for any number of objects

Example

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

const obj1 = { name: "Alice", email: "alice@email.com", age: 25 };
const obj2 = { name: "Bob", city: "New York", age: 30 };
const obj3 = { name: "Charlie", age: 35, country: "USA" };

const objectUnionReduce = (...objects) => {
    return objects.reduce((acc, obj) => {
        for (let key in obj) {
            if (acc[key]) {
                // Merge with existing property
                acc[key] = acc[key].concat(obj[key]);
            } else {
                // Add new property as array
                acc[key] = Array.isArray(obj[key]) ? obj[key] : [obj[key]];
            }
        }
        return acc;
    }, {});
};

console.log(objectUnionReduce(obj1, obj2, obj3));
{
  name: [ 'Alice', 'Bob', 'Charlie' ],
  email: [ 'alice@email.com' ],
  age: [ 25, 30, 35 ],
  city: [ 'New York' ],
  country: [ 'USA' ]
}

Time Complexity: O(n × m), where n is the number of objects and m is the average number of properties.
Space Complexity: O(k), where k is the total number of unique properties across all objects.

Comparison

Method Best For Flexibility Performance
for...in Loop Two objects Moderate Faster for 2 objects
reduce() Method Multiple objects High Better for many objects

Conclusion

Both approaches effectively calculate the union of objects in JavaScript. Use the for...in loop for simple two-object merging, while reduce() is more suitable for merging multiple objects dynamically.

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2026-03-15T23:19:00+05:30

768 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements