这个问题在这里已有答案:
下面是一个代码,如果CategoryId
相同,则添加金额,并为每个line item
创建一个新的CategoryId
。
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' }]
我找不到关联问题的解决方案。
您可以为对象创建密钥(在循环中),如下所示:
const key = JSON.stringify([o.CategoryId, o.Type]);
然后用this[o.CategoryId]
替换this[key]
。而已。
你可以使用reduce()
,findIndex()
和every()
来做到这一点。
reduce()
设置累加器到[]
。findIndex()
在ac
中找到所有键都相同的Object。every()
中使用findIndex()
来检查所有需要匹配的keys
是否具有相同的值。findIndex()
返回-1
将项目添加到ac
,否则在Amount
找到项目的index
let array = [
{ 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' }]
function addBy(arr,keys){
return arr.reduce((ac,a) => {
let ind = ac.findIndex(x => keys.every(k => x[k] === a[k]));
ind === -1 ? ac.push(a) : ac[ind].Amount += a.Amount;
return ac;
},[])
}
console.log(addBy(array,["CategoryId","Type"]));