问题描述
- 根所数组相同的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]
})
}
}
解决方案
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);
}
解决方案二:
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()
时间: 2024-10-30 13:56:10