如何通过属性值在JSON数组中累积值?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何通过属性值在JSON数组中累积值?相关的知识,希望对你有一定的参考价值。
我有一个像这样的数据的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循环中循环使用类别数组?
答案
您可以使用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);
另一答案
您可以使用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);
以上是关于如何通过属性值在JSON数组中累积值?的主要内容,如果未能解决你的问题,请参考以下文章