javascript合并相同元素的数组
varlist=[{"id":1,"num":1,"name":"西瓜"},{"id":1,"num":3,"name":"西瓜"},{"id":1,"num":5,"n...
var list = [{"id":1,"num":1,"name":"西瓜"},{"id":1,"num":3,"name":"西瓜"},{"id":1,"num":5,"name":"西瓜"}];
如何根据id相同,然后自动合并成同一个数组里面,并计算num的总和,最后输出:
var newList = [{"id":1,"num":9,"name":"西瓜"}]; 展开
如何根据id相同,然后自动合并成同一个数组里面,并计算num的总和,最后输出:
var newList = [{"id":1,"num":9,"name":"西瓜"}]; 展开
展开全部
function union(arr){
arr = arr || [];
var tmp = {};
for(var i = 0, len = arr.length; i < len; i++){
var obj = arr[i];
if(obj.id in tmp){
tmp[obj.id].num += obj.num;
}else{
tmp[obj.id] = obj;
}
}
var result = [];
for(var key in tmp){
result.push(tmp[key]);
}
return result;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询