JavaScript program to merge two objects into a single object and adds the values for same keys

JavascriptWeb DevelopmentObject Oriented Programming

We have to write a function that takes in two objects, merges them into a single object, and adds the values for same keys. This has to be done in linear time and constant space, means using at most only one loop and merging the properties in the pre-existing objects and not creating any new variable.

So, let’s write the code for this function −

Example

const obj1 = {
   value1: 45,
   value2: 33,
   value3: 41,
   value4: 4,
   value5: 65,
   value6: 5,
   value7: 15,
};
const obj2 = {
   value1: 34,
   value3: 71,
   value5: 17,
   value7: 1,
   value9: 9,
   value11: 11,
};
const mergeObjects = (obj1, obj2) => {
   for(key in obj1){
      if(obj2[key]){
         obj1[key] += obj2[key];
      };
   };
   return;
};
mergeObjects(obj1, obj2);
console.log(obj1);

Output

The output in the console will be −

{
   value1: 79,
   value2: 33,
   value3: 112,
   value4: 4,
   value5: 82,
   value6: 5,
   value7: 16
}
raja
Published on 24-Aug-2020 09:08:19
Advertisements