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
<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
Code Explanation
The spread operator spreads the properties of obj1 and obj2 into a new object (here it is union).
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
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
Method | Description | Use Case |
---|---|---|
Spread Operator | Simple and modern way to merge objects | Use for simple merging |
Object.assign() | Copies properties to a new object | Use for simple merging |
Lodash merge() | Deeply merges objects including nested objects | Use for complex and nested merging |
Custom Function | Use your own logic for merging two or multiple objects | Use 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
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
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.
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.
🏋️♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009
Leave a Reply