Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
JavaScript program to merge two objects into a single object and adds the values for same keys
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];
};
};
for(key in obj2){
if(!obj1[key]){
obj1[key] = obj2[key];
};
};
return obj1;
};
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,
value9: 9,
value11: 11
}
How It Works
The function uses two loops to merge the objects:
- First loop: Iterates through obj1 and adds values from obj2 for matching keys
- Second loop: Iterates through obj2 to add any keys that don't exist in obj1
Alternative Approach Using Object.assign()
For a more concise solution, you can use Object.assign() with a custom merge logic:
const obj3 = { a: 10, b: 20, c: 30 };
const obj4 = { a: 5, b: 15, d: 40 };
const mergeAndAdd = (target, source) => {
Object.keys(source).forEach(key => {
target[key] = target[key] ? target[key] + source[key] : source[key];
});
return target;
};
const result = mergeAndAdd(obj3, obj4);
console.log(result);
{ a: 15, b: 35, c: 30, d: 40 }
Conclusion
Both approaches effectively merge objects and add values for duplicate keys. The first method modifies the original object in-place, while the second uses modern JavaScript methods for cleaner code.
