2 u010205965 u010205965 于 2016.03.31 17:58 提问

根所数组相同的name,然后计算其对应值

下面这段代码是把如name=a的统计其数量,得出a:3,b:2,c:1,请问大神如果根据下面的代码实现a:3 price:33(些数字为同名name的price想加,10+11+12),
function aa(){
var list = [ {"name":"a", "price": "10"}, {"name":"a", "price": "11"}, {"name":"a", "price": "12"}, {"name":"b", "price": "20"},{"name":"b", "price": "21"},{"name":"c", "price": "30"}];
var list2 = [];
var listMap = {};
for (var i = 0, len = list.length, name, price, key; i < len; i++) {
name = list[i].name;
price = list[i].price;
key = id// + '-' + name; // key为id和name的组合,值为number
if (!!listMap[key]) {
listMap[key]++;
} else {
listMap[key] = 1;
}
}
for (var item in listMap) {
list2.push({
id: item[0],
// name: item.split('-')[1],
number: listMap[item]
})
}
}

2个回答

qq_15434587
qq_15434587   2016.03.31 18:20

function test_result(){
var list = [ {"name":"a", "price": "10"}, {"name":"a", "price": "11"}, {"name":"a", "price": "12"}, {"name":"b", "price": "20"},{"name":"b", "price": "21"},{"name":"c", "price": "30"}];
var result={};
$.each(list,function(i,v){
if(result[v.name]){
result[v.name] =result[v.name]*1 + v.price*1;
}else{
result[v.name] = v.price*1;
}
})

    console.info(result);
}

showbo
showbo   Ds   Rxr 2016.04.01 11:02


    function aa() {
        var list = [{ "name": "a", "price": "10" }, { "name": "a", "price": "11" }, { "name": "a", "price": "12" }, { "name": "b", "price": "20" }, { "name": "b", "price": "21" }, { "name": "c", "price": "30" }];
        var rst = {};
        for (var i = 0; i < list.length; i++) {
            rst[list[i].name] = rst[list[i].name] || { count:0, price: 0 };
            rst[list[i].name].count++;
            rst[list[i].name].price += parseFloat(list[i].price);
        }
        for(var attr in rst)alert(attr+'\n数量:'+rst[attr].count+'\n价格:'+rst[attr].price)
    }
    aa()
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!