首页 > 解决方案 > 在javascript中对具有相同ID的不同键的值求和

问题描述

我想知道如何在 javascript 中为相同 id 的相同 id 对象的多个键值求和,如何求和pricetotal在我的 obj 中我尝试了下面的代码

var obj = [{
  id: "1",
  price: 100,
  total: 200
}, {
  id: "1",
  price: 100,
  total: 200
}, {
  id: "2",
  price: 10,
  total: 200
}]

let newobj = obj.reduce((a, c) => {
  let filtered = a.filter(el => el.id === c.id);
  if (filtered.length > 0) {
    a[a.indexOf(filtered[0])].price += +c.price;
  } else {
    a.push(c);
  }
  return a;
}, []);
console.log(newobj);

预期输出:

result=[{
  id: "1",
  price: 200,
  total: 400
},{
  id: "2",
  price: 10,
  total: 200
}]

标签: javascriptjqueryarraysobject

解决方案


代替Array#filter,您可以Array#find直接使用并获取该对象,而无需稍后查找索引。

如果找到只需添加想要的属性pricetotal.

如果您不想改变原始数据,您可以获取对象的副本以进行推送。

a.push({ ...c });

var array = [{ id: "1", price: 100, total: 200 }, { id: "1", price: 100, total: 200 }, { id: "2", price: 10, total: 200 }],

result = array.reduce((a, c) => {
  let found = a.find(el => el.id === c.id);
  if (found) {
    found.price += c.price;
    found.total += c.total;
  } else {
    a.push(c);
  }
  return a;
}, []);

console.log(result);
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}


推荐阅读