【问题标题】:JavaScript merge objects with same key and sum their valuesJavaScript 合并具有相同键的对象并将它们的值相加
【发布时间】:2020-06-21 20:29:51
【问题描述】:

代码运行正常,但响应中缺少 name 参数。

var objArr= [{'location_id':1,'quantity':20,'name':'AB'},{'location_id':1,'quantity':20,'name':'AB'},{'location_id':3,'quantity':20,'name':'cd'}]

// first, convert data into a Map with reduce
let counts = objArr.reduce((prev, curr) => {
  let count = prev.get(curr.location_id) || 0;
  prev.set(curr.location_id, (curr.quantity + count),curr.name);
  return prev;
}, new Map());

// then, map your counts object back to an array
let reducedObjArr = [...counts].map(([location_id, quantity,name]) => {
  return {location_id, quantity,name}
})


console.log (reducedObjArr);

预期响应:

[
{"location_id":1,"quantity":40, "name":'AB'},
{"location_id":3,"quantity":20, "name":'cd'}
]

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    最简单的方法:

    const objArr = 
        [ { location_id: 1, quantity: 20, name: 'AB' } 
        , { location_id: 1, quantity: 20, name: 'AB' } 
        , { location_id: 3, quantity: 20, name: 'cd' } 
        ] 
         
    const sum = objArr.reduce((a,c)=>{
      let x = a.find(e=>e.location_id===c.location_id)
      if(!x) a.push(Object.assign({},c))
      else  x.quantity += c.quantity
      return a
    },[])
    
    console.log(sum)
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

      【解决方案2】:

      您可以通过解决较小的问题和设计可重用的函数来解决这个问题。

      第一组相关对象

      发件人:

      [ { location_id:1, quantity:20, name:'AB' }
      , { location_id:1, quantity:20, name:'AB' }
      , { location_id:3, quantity:20, name:'cd' }
      ]
      

      收件人:

      { AB: [ { location_id:1, quantity:20, name:'AB' }
            , { location_id:1, quantity:20, name:'AB' }
            ]
      , cd: [ { location_id:3, quantity:20, name:'cd' }
            ]
      }
      

      然后合并每个集合

      发件人:

      [ [ { location_id:1, quantity:20, name:'AB' }
        , { location_id:1, quantity:20, name:'AB' }
        ]
      , [ { location_id:3, quantity:20, name:'cd' }
        ]
      ]
      

      收件人:

      [ { location_id:1, quantity:40, name:'AB' }
      , { location_id:3, quantity:20, name:'cd' }
      ]
      

      const group_name =
        group_by('name');
      
      const sum_quantity =
        merge_key_with('quantity', (a, b) => a + b);
        
      const answer =
        Object.values(group_name(data)).map(sum_quantity);
        
      console.log(answer);
      <script>
      const data =
        [ { location_id:1, quantity:20, name:'AB' }
        , { location_id:1, quantity:20, name:'AB' }
        , { location_id:3, quantity:20, name:'cd' }
        ];
      
      const group_by =
        k => xs =>
          xs.reduce
            ( (acc, x) =>
                ( acc[x[k]]
                    ? acc[x[k]].push(x)
                    : acc[x[k]] = [x]
                , acc
                )
            , {}
            );
      
      const merge_key_with =
        (k, fn) => xs =>
          xs.slice(1).reduce
            ( (acc, o) =>
                ( acc[k] = fn(acc[k], o[k])
                , acc
                )
            , {...xs[0]}
            );
      </script>

      【讨论】:

        猜你喜欢
        • 2015-08-30
        • 1970-01-01
        • 2019-06-16
        • 2022-11-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-27
        • 1970-01-01
        • 2015-12-16
        相关资源
        最近更新 更多