Merging Objects Without Duplicates in JavaScript
In this article, we will see how to merge more complex objects or arrays based on unique values on two different objects. Let’s learn that technique together.
- Merging two or more objects
- Merging of object into an Array
- Merging two arrays
Merging of two or more objects
Using ES6 object destructuring(…), it is very easy to merge two objects.
let obj1 = {Name: 'Harry', Age: '15'}; let obj2 = { DOB, '01/12/2005'}; let mergeObj = {…obj1 ,…obj2}; console.log(mergeObj); // {Name: 'Harry', Age: '15', DOB, '01/12/2005'};
If both the object has same properties i.e same key, then it will merge the last object value. Check the below code for this.
let obj1 = {Name: 'Harry', Age: '15'}; let obj2 = { Name: 'Mr. Potter',DOB, '01/12/2005'}; let mergeObj = {…obj1 ,…obj2}; console.log(mergeObj); // {Name: 'Mr. Potter', Age: '15', DOB, '01/12/2005'};
Merge objects into an array of objects
This also be done by object destructuring.
let array1 = [{Name : 'Harry' ,Age : '15'},{Name: 'Ben', Age : '16'}]; let obj1 = {Name : 'Steve', Age: '15'}; let mergedArrayOfObj = […array1, obj1]; console.log(mergedArrayOfObj); //[{Name : 'Harry' ,Age : '15'},{Name: 'Ben', Age : '16'}, {Name : 'Steve', Age: '15'}];
Merging two arrays
let’s consider the below array for the example,
let arr1 = [44, 33, 22]; let arr2 = [33, 22, 11];
Using destructuring(…)
Merging two different array of objects is same as above, you need to destructure both the arrays.
let mergedArr = [...arr1, ...arr2]; // [44, 33, 22, 33, 22, 11];
Using Set
We can merge an array and create the distinct set of values out of it by using Set
.
let arrWithDup = [44, 33, 22, 33, 22, 11]; let distinctSet = new Set(arrWithDup); console.log(distinctSet); // Set {44, 33, 22, 11} let setToArr = [...distinctSet]; console.log(setToArr); // [44, 33, 22, 11]