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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay