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 can try this solution:
var arr = [{"a":4,"b":5, "d":6}, {"a":4, "c":5}, {"c":4}]; var result = {}; arr.forEach(function(obj) { for(var prop in obj) { if(obj.hasOwnProperty(prop)) { result[prop] = (result[prop] || 0) + obj[prop]; } } }); $('#result').text(JSON.stringify(result,null,2));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div id="result"></div>
_.merge
with a custom callback would do:
var array = [{"a": 4, "b": 5, "d": 6}, {"a": 4, "c": 5}, {"c": 4}]; var result = _.merge.apply(null, array.concat([function(a, b) { if (typeof a === 'number') { return a + b; } }])); console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js"></script>
As of lodash 4.0.0 this is simple using mergeWith :
_.mergeWith({}, ...array, _.add)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.