Sum all data in array of objects into new array of objects
Using for..in
to iterate object and reduce
to iterate array
var data = [{costOfAirtickets: 2500, costOfHotel: 1200},{costOfAirtickets: 1500, costOfHotel: 1000}];
var result = [data.reduce((acc, n) => {
for (var prop in n) {
if (acc.hasOwnProperty(prop)) acc[prop] += n[prop];
else acc[prop] = n[prop];
}
return acc;
}, {})]
console.log(result)
Use Lodash to simplify your life.
const _ = require('lodash')
let keys = ['costOfAirtickets', 'costOfHotel'];
let results = _.zipObject(keys, keys.map(key => _.sum( _.map(data, key))))
...
{ costOfAirtickets: 4000, costOfHotel: 2200 }
Explanation:
_.sum(_.map(data, key))
: generates sum of each array_.zipObject
: zips the results with the array sum- using
keys.map()
for sum of each key as_.map
does not guarantee order.
Documentation:
- sum: https://lodash.com/docs/4.17.10#sum
- zipObject: https://lodash.com/docs/4.17.10#zipObject
- map: https://lodash.com/docs/4.17.10#map