首页 > 解决方案 > 如果对象中有重复值,则 JavaScript 求和值

问题描述

我有一个对象:

const transaction = [{
  created: 1200,
  amount: 200
},{
  created: 1200,
  amount: 400
},{
  created: 1400,
  amount: 400
},{
  created: 1400,
  amount: 300
},{
  created: 1500,
  amount: 100
}]

每次created都具有相同的值,我想对amount对象的 's 求和。因此,例如created: 1200将有一个数量:600总计,因为 multiplecreated的位置在 1200 处,所以这个数量被加起来了。

标签: javascriptecmascript-6

解决方案


这是一个简单的解决方案,注意我编码很快,以便以后可以优化

const transaction = [{
  created: 1200,
  amount: 200
},{
  created: 1200,
  amount: 400
},{
  created: 1400,
  amount: 400
},{
  created: 1400,
  amount: 300
},{
  created: 1500,
  amount: 100
}];
// accepts an array of objects
function sumObj(objArr) {
  // an object to store the `created` and `amount` as key=>value
  var newObj = {};
  // loop over the objects in the array
  objArr.forEach(function(obj) {
    // if the key is present in `newObj` then we need to add the amount to it's value
    if(obj.created in newObj) {
      newObj[obj.created] += obj.amount;
    }else {
      // else just add the key and the amount as value
      newObj[obj.created] = obj.amount;
    }
  });
  //  create an array to store the final objects
  var arr = [];
  // loop over the properties in `newObj`
  for(var prop in newObj) {
    // push an object each time
    arr.push({created: Number(prop), amount: newObj[prop]});
  }
  // return the final result
  return arr;
}
// log it to see the output
console.log(sumObj(transaction));

注意:我注意到数组中的每个对象都是根据排序的,.created所以我想出了另一个解决方案,请注意,如果对象并不总是排序,那么请改用第一个解决方案

const transaction = [{
  created: 1200,
  amount: 200
},{
  created: 1200,
  amount: 400
},{
  created: 1400,
  amount: 400
},{
  created: 1400,
  amount: 300
},{
  created: 1500,
  amount: 100
}];
// accepts an array of objects
function sumObj(objArr) {
  // create an array to store the objects
  var newArr = [];
  // loop over the objects in the array
  objArr.forEach(function(obj, ind, arr) {
    // so since we check for the current object against the next one
    // we need to check when there is no next one to avoid errors
    // the idea is to check if the current object has the same .created
    // of the next object then add the amount to the next object
    // else check if this is the last object then just push it to the array
    // or if the current object has a different .created value then
    // just push it
    if(ind === arr.length - 1 || obj.created !== arr[ind + 1].created) {
      newArr.push(obj);
    }else {
      arr[ind + 1].amount += obj.amount;
    }
  });
  // return the result
  return newArr;
}
// print the result
console.log(sumObj(transaction));


推荐阅读