【问题标题】:Sum of Javascript value if two conditions are met [duplicate]如果满足两个条件,则 Javascript 值的总和 [重复]
【发布时间】: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


    【解决方案1】:

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

    1. reduce() 中将累加器设置为[]
    2. 然后使用findIndex()ac中找到所有key都相同的Object。
    3. 您需要在findIndex() 中使用every() 来检查所有需要匹配的keys 是否具有相同的值。
    4. 如果findIndex()返回-1,则将该项目添加到ac,否则在index找到的项目中增加Amount

    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"]));

    【讨论】:

    • 我会将另一个标记为答案,因为我实际上仍然需要代码来创建一个新数组,但感谢您的回答。
    • @klent 很好。您应该标记最佳答案。
    【解决方案2】:

    您可以像这样为您的对象创建密钥(在您的循环中):

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

    然后将this[o.CategoryId] 替换为this[key]。就是这样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-07
      • 1970-01-01
      • 1970-01-01
      • 2019-08-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-13
      • 2017-10-06
      相关资源
      最近更新 更多