合并具有相同键的对象并将它们的值相加

合并具有相同键的对象并将它们的值相加

代码按预期工作正常,但响应中缺少 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'}
]

最佳答案

最简单的方法:

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; }

关于JavaScript 合并具有相同键的对象并将它们的值相加,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62504053/

10-11 14:15