I would think this is a surprisingly common and simple question but I cant seem to find what Im looking for
If I had
var array = [{"a":4,"b":5, "d":6}, {"a":4, "c":5}, {"c":4}]
how do I sum the objects to get
{"a":8,"b":5,"c":9, "d":6}
using underscore, lodash, or something fairly quick and simple one liner?
You should be able to use reduce for this
var compact = array.reduce(function(prev,cur){
for(var key in cur){
if(!cur.hasOwnProperty(key))continue;
if(prev.hasOwnProperty(key)){
prev[key] += cur[key];
}else{
prev[key] = cur[key];
}
}
return prev;
},{});
You could combine spread(), merge(), and add() to produce:
_.spread(_.merge)([{}].concat(array, _.add));
// → { a: 8, b: 5, d: 6, c: 13 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With