var result={};
for(var i=0; i< arr.length; i++){
result[arr[i].id]=(result[arr[i].id]||0)+parseInt(arr[i].amount);
}
//取计算结果
for(var p in result){
console.log("id为"+p+" 的结果:"+result[p]);
}
应该可行
var count=[0,0] $.each(data,function(i){ if(data[i].id==1){ count[0]=count[0]+data[i].amount; }else{ //do somthing } });
var json = [{ "id": "1", "amount": "2" }, { "id": "2", "amount": "2" }, { "id": "1", "amount": "4"}]; var temp = new Array(); var result = new Array(); $.each(json, function (i, data) { var amount = 0; var str = temp.join(','); $.each(json, function (j, child) { if (data.id == child.id) { // 是否存在非冗余结果集 if (str.indexOf(child.id + ",") == -1) { temp[temp.length] = parseInt(child.id); } amount += parseInt(child.amount); } }); if (str.indexOf(data.id + ",") == -1) { result[i] = " ID:" + data.id + " amount: " + amount; } });
var arr = [{"id":"1", amount":"2"},{"id":"2", "amount":"2"},{"id":"1", "amount":"4"} ]; var count_1 = 0; //id为1的总数 var count_2 = 0; //id为2的总数 $.each(arr, function(index, item){ if(item.id==1){ count_1 = count_1 + parseInt(item.amount); }else if(item.id==2){ count_2 = count_2 + parseInt(item.amount); } });