javascript - 减少和分组对象数组
问题描述
这是我的对象数组。我正在谷歌表格中编写一个自定义脚本,以接收交易数据并将其分解为一个独特项目列表,其中将订购的金额相加以创建更容易阅读的购买历史记录。
products = [
{ id: 1,
item: 'Beef',
category: 'Meat',
orderAmount: 5,
caseSize: 1,
unit: 'Lb',
price: 50,
supplier: 'Sysco' },
{ id: 2,
item: 'Chicken',
category: 'Meat',
orderAmount: 10,
caseSize: 2,
unit: 'Grams',
price: 100,
supplier: 'Findlay' },
{ id: 3,
item: 'Fish',
category: 'Seafood',
orderAmount: 15,
caseSize: 3,
unit: 'Lb',
price: 40,
supplier: 'Deodato' },
{ id: 1, // This is an example duplicate entry
item: 'Beef',
category: undefined,
orderAmount: 100,
caseSize: 1,
unit: 'Lb',
price: 50,
supplier: 'Sysco' }
]
我对如何将其分解为另一个对象感到有些困惑,就像这样,其中重复的项目被删除,但重复项的 orderAmounts 被加起来。
uniqueProducts = [
{ id: 1,
item: 'Beef',
category: 'Meat',
orderAmount: 105, //this is the altered amount
caseSize: 1,
unit: 'Lb',
price: 50,
supplier: 'Sysco' },
{ id: 2,
item: 'Chicken',
category: 'Meat',
orderAmount: 10,
caseSize: 2,
unit: 'Grams',
price: 100,
supplier: 'Findlay' },
{ id: 3,
item: 'Fish',
category: 'Seafood',
orderAmount: 15,
caseSize: 3,
unit: 'Lb',
price: 40,
supplier: 'Deodato' }
]
我一直在阅读有关使用 map 和 reduce 函数的信息,但我很难弄清楚如何使用如此大的对象来实现它们。
解决方案
您可以将元素减少到 aMap
并累积orderAmount
:
const products = [ { id: 1, item: 'Beef', category: 'Meat', orderAmount: 5, caseSize: 1, unit: 'Lb', price: 50, supplier: 'Sysco' }, { id: 2, item: 'Chicken', category: 'Meat', orderAmount: 10, caseSize: 2, unit: 'Grams', price: 100, supplier: 'Findlay' }, { id: 3, item: 'Fish', category: 'Seafood', orderAmount: 15, caseSize: 3, unit: 'Lb', price: 40, supplier: 'Deodato' }, { id: 1, item: 'Beef', category: undefined, orderAmount: 100, caseSize: 1, unit: 'Lb', price: 50, supplier: 'Sysco' } ]
const reducedProductsMap = products.reduce((map, p) => {
const previousOrderAmount = map.get(p.id) !== undefined ? map.get(p.id).orderAmount : 0
let newP = {...p}
newP.orderAmount += previousOrderAmount
map.set(newP.id, newP)
return map
}, new Map());
console.log(Array.from(reducedProductsMap.values()));
推荐阅读
- ansible - 当我运行我的 Ansible-Playbook 时,我希望我的任务名称专门执行
- assembly - 将寄存器设置为 1 的首选方法
- javascript - 如何添加 JavaScript 警报消息以显示使用 JavaScript 的 html 表单验证是正确的
- reactjs - 组件颜色的初始渲染问题
- javascript - Javascript:尽管条件为真,但如果语句未执行,并且要执行的代码在 If 之外工作
- php - MAMP Mysql 似乎已正确安装,但无法正常工作,因为它应该在 Mac OS X 上安装 localhost
- git - 将 Git 非分支引用推送到远程
- c - 超时后杀死子进程,有多个孩子?
- c - 为什么a + = a在C中等于0?
- java - 在 Java 中是否可以在不使用关键字“implements”的情况下实现接口及其方法?