【发布时间】:2019-07-30 03:39:24
【问题描述】:
如果CategoryId 相同,下面是添加金额的代码,并根据CategoryId 创建一个新的line item。
self.OriginalLineItems = [
{ CategoryId: 'Cat1', Amount: 15, Type: 'TypeA' },
{ CategoryId: 'Cat1', Amount: 30, Type: 'TypeA' },
{ CategoryId: 'Cat1', Amount: 20, Type: 'TypeB' },
{ CategoryId: 'Cat2', Amount: 10, Type: 'TypeA' },
{ CategoryId: 'Cat2', Amount: 5, Type: 'TypeB' }]
self.newLineItems = [];
self.OriginalLineItems.forEach(function (o) {
if (!this[o.CategoryId]) {
this[o.CategoryId] = { CategoryId: o.CategoryId, Amount: 0, Type: o.Type };
self.newLineItems.push(this[o.CategoryId]);
}
this[o.CategoryId].Amount += o.Amount;
}, Object.create(null));
这将导致下面的数组:
self.newLineItems = [{ CategoryId: 'Cat1', Amount: 65, Type: 'TypeA' },
{ CategoryId: 'Cat2', Amount: 15, Type: 'TypeA' }]
但是我想添加一个新的条件是类型,我如何得到下面的结果?
self.newLineItems = [{ CategoryId: 'Cat1', Amount: 45, Type: 'TypeA' },
{ CategoryId: 'Cat1', Amount: 20, Type: 'TypeB' },
{ CategoryId: 'Cat2', Amount: 10, Type: 'TypeA' },
{ CategoryId: 'Cat2', Amount: 5, Type: 'TypeB' }]
我找不到链接问题的解决方案。
【问题讨论】:
标签: javascript arrays