求和数组的相同对象 [英] Sum the same object of array
本文介绍了求和数组的相同对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var data = [ {id:1, qty:100}, {id:2, qty:200}, {id:1, qty:100}, {id:2, qty:200} ];
如何将此数组求和为 [{id:1,qty: 200},{id:2,数量:400}];
Thx。
推荐答案
试试这个:
var sum = [];
data.forEach(function(o) {
var existing = sum.filter(function(i) { return i.id === o.id })[0];
if (!existing)
sum.push(o);
else
existing.qty += o.qty;
});
参见小提琴
这篇关于求和数组的相同对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文