如何通过属性值在JSON数组中累积值?

时间:2019-01-03 14:04:09

标签: javascript object

我有一个Json数组,其中包含这样的数据

0: Product {Name: "--Product Name--", CategoryID: "115", Sku: "xxxx", Quantity: 1, Price: 4}
1: Product {Name: "--Product Name--", CategoryID: "115", Sku: "xxxx", Quantity: 1, Price: 4}
2: Product {Name: "--Product Name--", CategoryID: "115", Sku: "xxxx", Quantity: 1, Price: 4}
3: Product {Name: "--Product Name--", CategoryID: "77", Sku: "xxxx", Quantity: 1, Price: 9.99}
4: Product {Name: "--Product Name--", CategoryID: "77", Sku: "xxxx", Quantity: 2, Price: 9.99}
5: Product {Name: "--Product Name--", CategoryID: "77", Sku: "xxxx", Quantity: 1, Price: 9.99}
6: Product {Name: "--Product Name--", CategoryID: "77", Sku: "xxxx", Quantity: 4, Price: 9.99}

我要根据对象的类别ID及其数量和成本来创建存储在对象中的产品的简要摘要

所以输出将类似于:

 Category Id    Quantity    Cost
     115           3        12
     77            8        79.92

是否有一种简单的方法,而无需创建多个数组来显示对象中的类别ID,并循环遍历每个产品数组,然后在嵌套的for循环中遍历类别数组?

2 个答案:

答案 0 :(得分:3)

您可以使用array#reduce将对象累加器中CategoryID上的数组分组。

let products = [{Name: "--Product Name--", CategoryID: "115", Sku: "xxxx", Quantity: 1, Price: 4},{Name: "--Product Name--", CategoryID: "115", Sku: "xxxx", Quantity: 1, Price: 4}, {Name: "--Product Name--", CategoryID: "115", Sku: "xxxx", Quantity: 1, Price: 4},{Name: "--Product Name--", CategoryID: "77", Sku: "xxxx", Quantity: 1, Price: 9.99}, {Name: "--Product Name--", CategoryID: "77", Sku: "xxxx", Quantity: 2, Price: 9.99}, {Name: "--Product Name--", CategoryID: "77", Sku: "xxxx", Quantity: 1, Price: 9.99},{Name: "--Product Name--", CategoryID: "77", Sku: "xxxx", Quantity: 4, Price: 9.99}],
    result = Object.values(products.reduce((r, o) => {
      r[o.CategoryID] = r[o.CategoryID] || {CategoryID: o.CategoryID, Quantity: 0, Price: 0};
      r[o.CategoryID]['Quantity'] += o.Quantity;
      r[o.CategoryID]['Price'] += o.Price;
      return r;
    }, {}));
console.log(result);

答案 1 :(得分:0)

您可以使用Array.reduce编写紧凑的代码,但也可以使用Array.forEach来提高清晰度:

// creates dummy data
let data = (new Array(100)).fill().map(() => ({
  id: Math.floor(3 * Math.random()),
  quantity: Math.random(),
  cost: Math.random()
}));

// summary object
let summary = {};

// add keys
data.forEach(d => {
  if (summary[d.id] == undefined) {
    summary[d.id] = {
      quantity: 0,
      cost: 0
    };
  }
});

// populate summary
data.forEach(d => {
  summary[d.id].quantity += d.quantity;
  summary[d.id].cost += d.cost;
});

console.log(summary);