我正在尝试使用reduce()
javascript 中的函数聚合数据(类似于这个问题):
HTML
Product 1: <button id="product1">Add one</button>
Product 2: <button id="product2">Add one</button>
JS
$('button').on('click', function() {
var pid = $(this).attr('id');
cart[cart.length] = {id:pid, qty:1}
var result = cart.reduce(function(res, obj) {
if (!(obj.id in res))
res.__array.push(res[obj.id] = obj);
else {
res[obj.id].qty += obj.qty;
}
return res;
}, {__array:[]})
console.log(result)
});
});
我无法使其工作,因为返回的数组不包含qty
数据。例如:
Object {__array: Array[1], product1: Object}
Object {__array: Array[1], product1: Object}
Object {__array: Array[2], product1: Object, product2: Object}
我正在寻找的结果更像是:
Object {product1: 1} //click on product1, quantity = 1
Object {product1: 2} //click on product1 again, quantity = 1 + 1 = 2
Object {product1: 2, product2: 1} //click on product2
我错过了什么?