
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Merge Two Objects into a Single Object in JavaScript
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 }
Advertisements