我有以下js见this fiddle。
var name = ["Ted", "Sarah", "Nancy", "Ted", "Sarah", "Nancy"];
var prodID = [111, 222, 222, 222, 222, 222];
var prodName = ["milk", "juice", "juice", "juice", "juice", "juice"];
var qty = [1, 2, 3, 3, 3, 1];
var data = {};
for (i = 0; i < name.length; i++) {
if (!data[name[i]]) {
purchased = {
"name": name[i],
"prodID": prodID[i],
"prodName": prodName[i],
"qty": qty[i]
};
data[name[i]] = purchased;
} else {
purchased = data[name[i]];
purchased.qty += +qty[i];
}
data[name[i]] = purchased;
}
data = $.map(data, function (val, key) {
return val;
});
data.sort();
$.each(data, function (i, val) {
var plural = "";
if (val.qty > 1) {
plural = "'s";
}
$('body').append(val.name + ' has purchased ' + val.qty + ' bottle' + plural + ' of ' + val.prodName + '<br>');
});
哪个输出
特德购买了4瓶牛奶 莎拉购买了5瓶果汁 南希购买了4瓶果汁
我想要做的是展示他们购买的每种产品以及每种产品的数量。
例如,看上面的Ted已经购买了1瓶牛奶和3瓶果汁,但我现在正在输出Ted已经购买了4瓶牛奶,因为4是他购买的总量。登记/> 如何按每个prodID / ProdName对其进行分组,以便我得到以下内容。
特德购买了1瓶牛奶和3瓶果汁 莎拉购买了5瓶果汁 南希购买了4瓶果汁
答案 0 :(得分:2)
第一步是将数据结构转换为更合适的结构,例如:
name.forEach(function(nam, i) {
data[nam] = data[nam] || {};
pid = prodID[i];
data[nam][pid] = data[nam][pid] || {total:0, pname: prodName[i]};
data[nam][pid].total += qty[i];
});
给你
"Ted": {
"111": {
"total": 1,
"pname": "milk"
},
"222": {
"total": 3,
"pname": "juice"
}
},
"Sarah": {
"222": {
"total": 5,
"pname": "juice"
}
},
"Nancy": {
"222": {
"total": 4,
"pname": "juice"
}
}
鉴于此,生成输出非常简单:
message = Object.keys(data).map(function(nam) {
var purchases = data[nam];
return nam + ' got ' + Object.keys(purchases).map(function(pid) {
return purchases[pid].total + ' bottle(s) of ' + purchases[pid].pname
}).join(' and ');
}).join(' <br> ');
(复数留作练习,请注意正确的表单是bottles
,而不是bottle's
。