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 = {
  "key1":5,
  "key2":8,
  "key3":6
}

let obj2 = {
  "key1":3,
  "key2":7,
  "key4":9
}

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

let output = {
  "key1":8, 
  "key2":15,
  "key3":6,
  "key4":9
}

How do I do this in vanilla JavaScript?
Thanks

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.