如何通过任意一组键对数组元素进行分组?

时间:2015-08-13 16:50:04

标签: javascript arrays

拥有一个对象数组,我想通过组合不同的键集来对值进行求和。更具体地说,有一系列物品,描述这顿饭(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)的值求和的最有效方法是什么?

1 个答案:

答案 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;
&#13;
&#13;