如果满足两个条件,则Javascript值的总和[重复]

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

这个问题在这里已有答案:

下面是一个代码,如果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' }]

我找不到关联问题的解决方案。

javascript arrays
2个回答
3
投票

您可以为对象创建密钥(在循环中),如下所示:

const key = JSON.stringify([o.CategoryId, o.Type]);

然后用this[o.CategoryId]替换this[key]。而已。


4
投票

你可以使用reduce()findIndex()every()来做到这一点。

  1. reduce()设置累加器到[]
  2. 然后使用findIndex()ac中找到所有键都相同的Object。
  3. 您需要在every()中使用findIndex()来检查所有需要匹配的keys是否具有相同的值。
  4. 如果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"]));
© www.soinside.com 2019 - 2024. All rights reserved.