I have an array of objects that looks like this:
var data = [{costOfAirtickets: 2500, costOfHotel: 1200},{costOfAirtickets: 1500, costOfHotel: 1000}]
Here is a lodash
approach
_(data).flatMap(_.entries).groupBy(0).mapValues(v=>_.sumBy(v, 1)).value()
It will sum by all the unique keys.
var data = [{costOfAirtickets: 2500, costOfHotel: 1200},{costOfAirtickets: 1500, costOfHotel: 1000}];
var res = _(data).flatMap(_.entries).groupBy(0).mapValues(v=>_.sumBy(v, 0)).value();
console.log(res);
Wrap your result to a [...]
or use a .castArray()
at the end before unwrapping using .value()
in case you want a array as result.