DEV Community

Rahul Nayak
Rahul Nayak

Posted on

2 1

How to merge JS objects with common keys

While working on a project, I came across a situation where I had to merge 2 objects with common keys. In this post, I'll show you a simple solution to merge the objects.

Problem statement:

We have 2 objects(originalObject and objectToMerge) and each object has a few keys which are common in both the objects. If the key is common, we want to add the values from both the objects and store the updated value in originalObject. If it isn't, then we want to add the new key to the originalObject.
Here's an example:

let originalObject = {
  key1:1,
  key2:2,
  key3:3,
  key4:4
}

let objectToMerge = {
  key2:5,
  key6:6,
  key3:-7
}

// Output after merging

originalObject = {
 key1: 1,
 key2: 7, // 2+5 = 7
 key3:-4, // 3+(-7) = -4
 key4: 4,
 key6: 6
}

Enter fullscreen mode Exit fullscreen mode

Solution:

let originalObject = {
  key1:1,
  key2:2,
  key3:3,
  key4:4
}

let objectToMerge = {
  key2:5,
  key6:6,
  key3:-7
}

let keys = Object.keys(objectToMerge)

keys.forEach((key) => {
if(originalObject.hasOwnProperty(key)) {
   originalObject[key] += objectToMerge[key]
}
else {
  originalObject[key] = objectToMerge[key]
}
})

console.log(originalObject)
Enter fullscreen mode Exit fullscreen mode

Code explanation
I used the keys method on originalObject object to extract all the keys name.
Next we will loop through these keys and check if each key is present in the objectToMerge object.

If the key is present in both the objects, then we will add the values of the two and store it in originalObject. If not, we will create a new key in the originalObject object. And that's it!!

Feel free to play around with the code present here.

A lot of libraries have this logic inbuilt as an utility function but I wanted a simple Vanilla JS solution hence this approach. I have found one such solution in Lodash. You can find it here.


Let me know if you solved this any other way. Would love to hear more ways to solve this problem.

Until next post. ta-da!

Top comments (0)

๐Ÿ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someoneโ€™s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay