How to merge 2 objects and update the common object keys

Hi guys,

So I have 2 objects and some object keys are common in both of them. I want to merge the 2 objects so that the values of the common keys add up upon merging.

For example, I have 2 objects as below

let obj1 = {

let obj2 = {

Once the 2 objects are merged, the output should look like this:

let output = {

How do I do this in vanilla JavaScript?

If you do not want to mutate the existing objects, then you can start by making a copy of obj1 into a new object (let’s call it mergedObj) and iterate through the keys of obj2.
During each iteration, check if mergedObj has has a key of obj2. If it does, then create a new key in the mergedObj and set its value to the sum of mergedObj`` and obj2keys' values. IfmergedObjdoes not have the key, then you can just create a new key with the value ofobj2`'s key value.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.