CodersTechZone
  • .NET
    • C#
    • ASP.Net
  • HTML
  • Javascript
  • CSS
  • Database
    • SQL Server
    • MYSql
    • Oracle
  • AI
  • TechNews
  • Web-Stories

JavaScript Union Two Objects: 4 Powerful Methods

Shawpnendu Bikash Maloroy

July 29, 2024
JavaScript Union Two Objects- 4 Powerful Methods
Spread the love

Understanding JavaScript union two objects efficiently is crucial for JS developers in various scenarios. From merging data to combining configurations and even aggregating API results, the JavaScript union two objects helped us a lot to display clear and concise data to users.

In this article, I am going to explain each possible method to do this union through JS code examples and explanations.

Table of Contents

  • JavaScript Union Two Objects: Four Different Methods
    • 1. Using the Spread Operator
      • Output
      • Code Explanation
    • 2. Using Object.assign()
    • 3. Using Lodash’s .merge()
    • 4. Using Custom Function
      • Output
      • Code Explanation
  • JavaScript Union Two Objects: Four Different Methods Comparison
  • Three More Practical Examples for Your Practice
    • Example 1: Merging User Profiles
      • Output
    • Example 2: Combining API Responses
      • Output
      • Code Explanation
    • Example 3: Merging User Configurations
  • Best Practices
  • Conclusion

JavaScript Union Two Objects: Four Different Methods

1. Using the Spread Operator

<script>

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

    // JavaScript Union Two Objects
    const union = { ...obj1, ...obj2 };
    console.log(union); // { a: 1, b: 3, c: 4 }

    // JavaScript Union Three Objects
    const union2 = { ...obj1, ...obj2, ...obj3 };
    console.log(union2); // { a: 1, b: 4, c: 5 }

</script>

Output

JavaScript Union Two Objects - using the Spread Operator
JavaScript Union Two Objects – using the Spread Operator

Code Explanation

The spread operator spreads the properties of obj1 and obj2 into a new object (here it is union).

Note

If both objects have the same property (‘b’ in this case), the value from the second object (obj2) will override the value from the first (obj1). JavaScript Union Objects follow the same rule irrespective of the number of sets.

buymeacoffee

2. Using Object.assign()

<script>

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

    // Using Object.assign Method
    // JavaScript Union Two Objects
    const union =Object.assign(obj1,obj2);
    console.log(union); // { a: 1, b: 3, c: 4 }

    // JavaScript Union Three Objects
    const union2 = Object.assign(obj1,obj2,obj3);
    console.log(union2); // { a: 1, b: 4, c: 5 }

</script>

The Object.assign() method copies the properties of obj1 and obj2 into a new object here named union.

As mentioned in the earlier note, the order of the arguments determines which properties will override others in cases of common properties. Here, in this case, obj2 common properties override the obj1 properties. If you alter the order, like object.assign(obj2,obj1), then the obj1 common properties override the obj2 properties. Concept is clear now, right?

3. Using Lodash’s .merge()

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
<script>

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

    const union = _.merge({}, obj1, obj2);
    console.log(union); 
    // { a: 1, b: { x: 1, y: 2 }, c: 4 }
    
</script>

Lodash is a popular 3rd party JS utility library that provides us a merge() function for deep merging objects.

4. Using Custom Function

By using a custom function, we can marge complex objects based on our logic. Look at the below custom function to merge two or multiple objects. You can merge nested properties like this way:

<script>

    // Custom function to merge objects
    // Can merge deep properties
    function mergeObjects(obj1, obj2) {
        const union = {};

        for (let key in obj1) {
            union[key] = obj1[key];
        }

        for (let key in obj2) {
            if (union[key] && typeof union[key] === 'object' && typeof obj2[key] === 'object') {
                union[key] = mergeObjects(union[key], obj2[key]);
            } else {
                union[key] = obj2[key];
            }
        }

        return union;
    }

    // List of nested objects
    const obj1 = { a: 1, b: { x: 1 } };
    const obj2 = { b: { y: 2 }, c: 4 };

    // deep copying example
    const union = mergeObjects(obj1, obj2);
    console.log(union); 
    // { a: 1, b: { x: 1, y: 2 }, c: 4 }

</script>

Output

JavaScript Union Two Objects - using custom function
JavaScript Union Two Objects – using custom function

Code Explanation

Custom Function “mergeObjects” loops through the properties of both objects. Deep merge the nested objects properties by recursive calling. Finally return the “union” object to the caller function.

JavaScript Union Two Objects: Four Different Methods Comparison

MethodDescriptionUse Case
Spread OperatorSimple and modern way to merge objectsUse for simple merging
Object.assign()Copies properties to a new objectUse for simple merging
Lodash merge()Deeply merges objects including nested objectsUse for complex and nested merging
Custom FunctionUse your own logic for merging two or multiple objectsUse for advanced control and own customization

Three More Practical Examples for Your Practice

Example 1: Merging User Profiles

The below code example will combine user profile data from two different sources.

<script>
    
    const userDefaults = { name: "Shawpnendu Bikash", timeout: 45, preferences: { theme: "dark" } };
    const userSettings = { timeout: 25, preferences: { language: "en" } };

    const userProfile = { ...userDefaults, ...userSettings };
    console.log(userProfile); 
    
</script>

Output

JavaScript Union Two Objects - Merging User Profiles
JavaScript Union Two Objects – Merging User Profiles

Example 2: Combining API Responses

Check how to merge data from multiple API responses into a single object.

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
<script>

    const apiResponse1 = { id: 1, data: { items: [1, 2] } };
    const apiResponse2 = { data: { items: [3, 4] }, status: "success" };

    const combinedResponse1 = _.merge({}, apiResponse1, apiResponse2);
    const combinedResponse2 = _.mergeWith({}, apiResponse1, apiResponse2,customizer);
    const combinedResponse3 =Object.assign(apiResponse1, apiResponse2);
    const combinedResponse4 ={...apiResponse1, ...apiResponse2};
    const combinedResponse5=_.assign({}, apiResponse1, apiResponse2)

    console.log(combinedResponse1); 
    console.log(combinedResponse2); 
    console.log(combinedResponse3); 
    console.log(combinedResponse4); 
    console.log(combinedResponse5); 

    // { id: 1, data: { items: [3, 4] }, status: "success" } except mergeWith
    // { id: 1, data: { items: [1,2,3, 4] }, status: "success" } using mergeWith

    function customizer(objValue, srcValue) {
    if (_.isArray(objValue)) {
        return objValue.concat(srcValue);
    }
}
    
</script>

Output

JavaScript Union Two Objects - Merging Arrays
JavaScript Union Two Objects – Merging Arrays
buymeacoffee

Code Explanation

Except the lodash mergeWith method, all other methods remove elements from an array, though values are unique. Only the mergeWith method can successfully combine all unique values of both arrays. Explained custom methods also return all unique values of both arrays, like the lodash mergeWith method. Print JS array into the console to avoid data loss.

Note

Read carefully the Lodash merge & mergeWith method from their document to understand the 3rd parameter and the other 5 possible values.

Example 3: Merging User Configurations

<script>
    const defaultConfig = { apiEndpoint: "https://api.example.com", timeout: 5000 };
    const userConfig = { timeout: 10000, debug: true };

    const finalConfig = { ...defaultConfig, ...userConfig };
    console.log(finalConfig); 
    // { apiEndpoint: "https://api.example.com", timeout: 10000, debug: true }
    // timeout taken from userConfig object - see earlier notes

</script>

Best Practices

So far, I have described all possible combinations to know JavaScript union two objects one by one with JS code examples and explanations.

Now the main question is which method or approach we must take to do a union set operation of two objects. Don’t worry, I am just explaining:

  • Use the spread operator or Object.assign() for simple merges, and _.merge() or a custom function for deep merges.
  • Make sure that nested objects are merged correctly without losing any data.
  • Maintaining object ordering is a must, as it affects which properties override others.
  • Use Lodash mergeWith or a custom method (mentioned in #4) to make a unique array.

Conclusion

Know-how of JavaScript union two objects is a must for web developers. Whether you are working with user data, API responses, or application configurations, merging objects will surely give you a pain in terms of data loss.

By using methods like the spread operator, Object.assign(), Lodash’s _.merge(), or custom functions, you can check my every example to get your expected results.

So, I am requesting that you follow the examples and best practices that I have mentioned in this guide to avoid confusions on object merging in JavaScript.

Shawpnendu Bikash Maloroy
Shawpnendu Bikash Maloroy

🏋️‍♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨‍✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Spread the love
«Previous
Next»

Leave a Reply Cancel reply

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

  • 7 Weird JavaScript Tricks That Look Like Bugs
    7 Weird JavaScript Tricks That Look Like Bugs (#3 Will Shock You!)
  • Build a JavaScript Gamer Journal in 8 Lines
    🎮 Build a JavaScript Gamer Journal in 8 Lines: Track Your Wins Like a Pro! 🏆
  • JavaScript Pet Feeder Reminder in 7 Lines
    How to Code a Simple JavaScript Pet Feeder Reminder in 7 Lines: Feed Your Pet Like a Coding Boss! 🐶
  • 10-line calculator JavaScript
    Build a Simple Calculator in JavaScript: 10 Lines to Wow Your Friends!
  • JavaScript No-Code Automation
    JavaScript No-Code Automation: How to Replace Zapier with a Few Lines of Code

About-CodersTech Zone |  Contact |  Disclaimer |  Fact-Checking policy |  Affiliate Disclosure |  Privacy Policy

Copyright © 2024 CodersTechZone.com