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

问题描述 投票:-2回答:2

我有一个像这样的数据的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循环中循环使用类别数组?

javascript object
2个回答
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);

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);
© www.soinside.com 2019 - 2024. All rights reserved.