- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript Sum of two objects with same properties
Suppose, we have two objects like these −
const obj1 = { a:12, b:8, c:17 }; const obj2 = { a:2, b:4, c:1 };
We are required to write a JavaScript function that takes in two such object.
The function should sum the values of identical properties into a single property. Therefore, the final object should look something like this −
const output = { a:14, b:12, c:18 };
Note − For the sake of simplicity, we have just used two objects, but we are required to write our function such that it can take in any number of objects and add their property values.
Example
const obj1 = { a:12, b:8, c:17 }; const obj2 = { a:2, b:4, c:1 }; const sumObjectsByKey = (...objs) => { const res = objs.reduce((a, b) => { for (let k in b) { if (b.hasOwnProperty(k)) a[k] = (a[k] || 0) + b[k]; } return a; }, {}); return res; } console.log(sumObjectsByKey(obj1, obj2));
Output
And the output in the console will be −
{ a: 14, b: 12, c: 18 }
Advertisements