首页 新闻 赞助 找找看

jQuery 数组 取值相加

0
悬赏园豆:20 [已解决问题] 解决于 2013-04-23 13:39

jQuery  中数组,Json 格式 [{"id":"1" ",amount":"2"},{"id":"2" "amount":"2"}{"id":"1" "amount":"4"}

]

我想得到id为1的总和,id为2的总和 

MissJacker的主页 MissJacker | 初学一级 | 园豆:59
提问于:2012-11-09 16:41
< >
分享
最佳答案
0

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]);

}

收获园豆:5
向往-SONG | 老鸟四级 |园豆:4853 | 2012-11-09 16:53

应该可行

学学学习 | 园豆:427 (菜鸟二级) | 2012-11-09 17:22
其他回答(3)
0
var count=[0,0]
$.each(data,function(i){
    if(data[i].id==1){
        count[0]=count[0]+data[i].amount;
    }else{
        //do somthing
     }
});
收获园豆:5
az235 | 园豆:8483 (大侠五级) | 2012-11-09 17:13
0
 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;
        }
    });
收获园豆:5
sym_cn | 园豆:798 (小虾三级) | 2012-11-09 18:19
0
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);
    }
});
收获园豆:5
程序猿小卡 | 园豆:386 (菜鸟二级) | 2012-12-08 00:42
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册