u010205965 于 2016.03.31 17:58 提问

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