我有一个这样的数组:
var data = [
{ catNumber: 'EK-21200', quantity: 5},
{ catNumber: 'EK-00341', quantity: 5},
{ catNumber: 'EK-21200', quantity: 5},
{ catNumber: 'EK-21200', quantity: 5},
{ catNumber: 'EK-00341', quantity: 5}
];
我希望结果总结相同catNumber的所有数量。
var data = [
{ catNumber: 'EK-21200', quantity: 15},
{ catNumber: 'EK-00341', quantity: 10}
];
答案 0 :(得分:2)
您可以使用此ES6代码:
var data = [
{ catNumber: 'EK-21200', quantity: 5},
{ catNumber: 'EK-00341', quantity: 5},
{ catNumber: 'EK-21200', quantity: 5},
{ catNumber: 'EK-21200', quantity: 5},
{ catNumber: 'EK-00341', quantity: 5}
];
data = Array.from(data.reduce( (acc, {catNumber, quantity}) =>
acc.set(catNumber, (acc.get(catNumber) || 0) + quantity),
new Map()
), ([catNumber, quantity]) => ({catNumber, quantity}) );
console.log(data);
或者,在ES5版本中:
var data = [
{ catNumber: 'EK-21200', quantity: 5},
{ catNumber: 'EK-00341', quantity: 5},
{ catNumber: 'EK-21200', quantity: 5},
{ catNumber: 'EK-21200', quantity: 5},
{ catNumber: 'EK-00341', quantity: 5}
];
var acc = data.reduce( function(acc, obj) {
acc[obj.catNumber] = (acc[obj.catNumber] || 0) + obj.quantity;
return acc;
}, {});
data = Object.keys(acc).map(function(key) {
return { catNumber: key, quantity: acc[key] };
});
console.log(data);
最后,这是一个不使用reduce
或map
等数组迭代方法的版本,而是使用for
循环:
var data = [
{ catNumber: 'EK-21200', quantity: 5},
{ catNumber: 'EK-00341', quantity: 5},
{ catNumber: 'EK-21200', quantity: 5},
{ catNumber: 'EK-21200', quantity: 5},
{ catNumber: 'EK-00341', quantity: 5}
];
var acc = {};
for (var i = 0; i < data.length; i++) {
var obj = data[i];
if (!acc[obj.catNumber]) acc[obj.catNumber] = 0;
acc[obj.catNumber] += obj.quantity;
}
data = [];
for (var key in acc) {
data.push({ catNumber: key, quantity: acc[key] });
}
console.log(data);