Overview
Often in JavaScript, it is necessary to combine multiple objects into a single object when dealing with various tasks like handling API requests, managing data, or creating software applications. Having the ability to merge objects is crucial for these scenarios.
Combining two elements to form a single entity is a fundamental process. The result can either replace an existing entity or be saved as a new one. Likewise, we can consolidate multiple attributes of two objects into a unified entity and manipulate them collectively by merging them using JavaScript.
However, how does it occur?
In JavaScript, a fundamental object is symbolized by a series of key-value pairs separated by commas. Each key corresponds to a specific value within the collection. When we aim to combine two objects, their attributes are consolidated and stored in a unified parent object. Interested to know more? Let's delve into the scenario where identical keys exist. What happens in such a case? This is where understanding shallow and deep merges is crucial. Let's explore this concept further through practical examples.
How to combine two JavaScript objects
Combine items employing the spread operator(…)
The spread syntax in JavaScript is a native feature that enables the merging of two JavaScript objects by expanding an iterable entity (like an array, object, etc.) passed to it into separate elements. This functionality not only enhances the clarity of our code but also helps in keeping it concise.
JavaScript objects can be shallowly copied using the spread operator. In the upcoming sections, we will delve into the concept of shallow copies. However, for now, let's define it as follows: when we combine two objects with the spread(...) operator, the existing value gets replaced if there are matching keys.
// initializing the first object
const obj1 = {
val1: 1,
val2: 2,
};
// initializing the second object
const obj2 = {
num1: 1,
num2: 2,
};
// merging both objects using spread(...) operator
const mergedObj = {
...obj1,
...obj2,
};
// printing the merged object
console.log(mergedObj);
Output
Combining objects using the Object.assign technique
One way to merge two JavaScript objects is by using the built-in function Object.assign. This function creates a new object that contains all the enumerable properties of the original objects copied into it.
The way it's written is
Syntax:
Object.assign(target, ...sources)
In the following example, an empty object is passed as the initial parameter to the Object.assign function. This approach is chosen to ensure that the returned object contains the combined values of all the input sources – specifically, obj1 and obj2.
In an alternative approach, sending the specific object as the initial parameter enables us to achieve the objective of combining all the source objects into the current object.
// initializing the first object
const obj1 = {
val1: 1,
val2: 2,
};
// initializing the second object
const obj2 = {
num1: 1,
num2: 2,
};
// merging both objects using the Object.assign() property
const mergedObj = Object.assign({}, obj1, obj2);
// printing the merged object
console.log(mergedObj);
Output
The Shallow Merge
The merging technique known as shallow merge is commonly used in JavaScript to combine two JS objects. However, there is a key consideration: during a shallow merge, if both objects contain keys with identical names, the value from the second object will overwrite the value from the first object. This process does not involve inspecting whether the targeted element is deeply nested or contains any sub-objects with distinct keys; it simply performs a complete replacement.
To gain a deeper comprehension, let's examine a demonstration.
// initializing the first object
const obj1 = {
num1: 1,
num2: {
subNum2_1 : 10,
subNum1_1: 20,
}
}
// initializing the second object
const obj2 = {
num3 : 3,
num2 : {
subNum2_3 : 15,
}
}
// merging both objects using the spread(...) operator
const mergedObj = {
...obj1,
...obj2,
}
// printing the merged object
console.log(mergedObj);
Output
In this scenario, we can see that the property num2 is shared between obj1 and obj2. When we performed a shallow merge on them, the original object holding the value of num2 was substituted with a new object containing obj2's value for the num2 key.
Deep Merge
Unlike shallow merging, deep merging involves traversing nested objects to merge them. During deep merging, identical keys are not immediately replaced; instead, the process checks for nested objects and continues until reaching the base level of the key. If two identical keys are found without nested children, they are replaced; otherwise, the child key is concatenated to the correct location in the parent object. This concept can be better understood through an example.
// initialization of the first object
const object1 = {
number1: 1,
number2: {
subNumber2_1: 10,
subNumber2_2: 20,
}
}
// initialization of the second object
const object2 = {
number3: 3,
number2: {
subNumber2_3: 30,
}
}
// merging both objects object1 and object2 using the spread(...) operator
const mergedObj = {
...object1,
...object2,
number2: {
...object1.number2,
...object2.number2,
},
}
// resulting of the merged object
console.log(mergedObj);
Output
In this instance, when object1 and object2 are deeply merged, the complete object is not immediately replaced. Instead, the process involves accessing the nested object, searching for matching keys, and then, since no identical keys exist at the top level, merging them at the correct position within the parent object.
Using custom functions to combine items
Furthermore, we have the option to develop a custom JavaScript function for merging two objects.
//using custom function to merge javascript objects
const merge = (...arguments) => {
let target = {};
let merger = (obj) => {
for (let prop in obj) {
if (obj.hasOwnProperty(prop)) {
target[prop] = obj[prop];
}
}
};
for (let i = 0; i < arguments.length; i++) {
merger(arguments[i]);
}
return target;
}
// initialization of the first object
const object1 = {
number1: 1,
number2: 2,
}
// initialization of the second object
const object2 = {
number3: 3,
number4: 4,
}
// usage of the merge() function
const mergedObj = merge(object1, object2);
// resulting the output
console.log(mergedObj);
Output
In this scenario, we commence by initializing object1 and object2, followed by invoking the merge function with the newly instantiated objects as arguments. Within the merge function, the spread operator is leveraged to receive arguments and establish an empty object to amalgamate the components. Inside this function, a helper function called merger is employed to merge the provided elements. This function takes an object as input and iterates through its constituents. Subsequently, a conditional statement is utilized to check if the given object contains a property; if affirmative, the element is assigned to the empty target object, and this process recurs until the entire object is traversed. Upon completion, the target object is returned and displayed.
The Lodash merge method
We can combine two JavaScript objects by utilizing the merge function provided by the lodash library.
// using the lodash library
const _ = require("lodash");
// initialization of object 1
let object1 = {
number1: [{ number1_1: 10, }, { number1_2: 20, }]
}
// initialization of object 2
let object2 = {
number1: [{ number2_1: 30, }, { number2_2: 40, }]
}
// merging the both objects
let object3 = _.merge(object1, object2);
// resulting the output
console.log(object3);
Output
In this instance, we demonstrate the utilization of the _.merge method from the lodash library to combine two objects. This function systematically integrates attributes from the source object into the target object. It ensures that when keys match, the values are appended rather than replaced. Employ the JavaScript Beautifier tool to improve the appearance of our code.
Conclusion
- In our programme, we usually need to combine many JavaScript objects.
- There are several ways to achieve this. Consider JavaScript's spread operator and the Object.assign function.
- When combining two JS objects, remember the notions of Shallow combining and Deep Merging.
- When two items have identical keys, Shallow Merging replaces the whole content of the first object.
- Deep Merging identifies and replaces conflicting nested values during overwriting.
- We can create our own JavaScript method to combine two items.