拥有一个对象数组,我想通过组合不同的键集来对值进行求和。更具体地说,有一系列物品,描述这顿饭(0 - 早餐,1 - 小吃......),我想做两个不同的总和:
对象数组示例如下:
var arrayIngredients = [{mealNumber: 4, name: "Sugars, total", quantity: 1.4300000000000002}, {mealNumber: 4, name: "Magnesium, Mg", quantity: 14.950000000000001}, {mealNumber: 3, name: "Vitamin A, IU", quantity: 27.9}]
有谁知道对给定密钥(名称)或多个密钥(mealNumber,name)的值求和的最有效方法是什么?
答案 0 :(得分:1)
您需要使用Array.prototype.reduce
(不需要第三方库)。
运行以下代码段以获取详细示例:
var arrayIngredients = [{
mealNumber: 4,
name: "Sugars, total",
quantity: 1.4300000000000002
}, {
mealNumber: 4,
name: "Magnesium, Mg",
quantity: 14.950000000000001
}, {
mealNumber: 3,
name: "Vitamin A, IU",
quantity: 27.9
}];
var dayTotals = arrayIngredients.reduce(function(result, next) {
if (!result.hasOwnProperty(next.name))
result[next.name] = {
totalQuantity: 0
};
result[next.name].totalQuantity += next.quantity;
return result;
}, {}); // this empty object is injected as "result" argument
// in the Array.prototype.reduce callback #1 parameter
document.getElementById("result").textContent = JSON.stringify(dayTotals);

<div id="result"></div>
&#13;