【问题标题】:ES6: Find objects containing object ID in array, and combine totals [duplicate]ES6:在数组中查找包含对象 ID 的对象,并合并总计 [重复]
【发布时间】:2020-02-23 15:27:33
【问题描述】:

给定一个这样的对象数组:

[
  {
    playerId: 1,
    playerName: "Cooper",
    assists: 1,
    points: 5,
  },
  {
    playerId: 1,
    playerName: "Cooper",
    assists: 3,
    points: 2,
  },
  {
    playerId: 2,
    playerName: "Tom",
    assists: 1,
    points: 3,
  },
  {
    playerId: 2,
    playerName: "Tom",
    assists: 3,
    points: 1,
  },
  {
    playerId: 3,
    playerName: "Shelby",
    assists: 2,
    points: 7,
  },
  {
    playerId: 3,
    playerName: "Shelby",
    assists: 1,
    points: 2,
  },
]

有没有办法使用 ES6 在对象数组中找到匹配的对象键(本例中为 playerId),然后为这些匹配组合其他对象键(助攻和点),因此最终数组看起来像这样:


[
  {
    playerId: 1,
    playerName: "Cooper",
    assists: 4,
    points: 7,
  },
  {
    playerId: 2,
    playerName: "Tom",
    assists: 4,
    points: 4,
  },
  {
    playerId: 3,
    playerName: "Shelby",
    assists: 3,
    points: 9,
  },
]

【问题讨论】:

标签: javascript arrays


【解决方案1】:

您可以使用Array.prototype.reduce() 来累积属性,通过减少到首先以playerId 作为键的对象进行跟踪,然后使用Object.values() 按预期取回数组。

let arrIn = [{"playerId":1,"playerName":"Cooper","assists":1,"points":5},{"playerId":1,"playerName":"Cooper","assists":3,"points":2},{"playerId":2,"playerName":"Tom","assists":1,"points":3},{"playerId":2,"playerName":"Tom","assists":3,"points":1},{"playerId":3,"playerName":"Shelby","assists":2,"points":7},{"playerId":3,"playerName":"Shelby","assists":1,"points":2}];

let arrOut = Object.values(arrIn.reduce((acc, current) => {
  let base = acc[current.playerId];
  if (!base) {
    // if we have not processed an object with this playerId yet,
    // simply copy the current object
    acc[current.playerId] = current;
  } else {
    // otherwise, increase the properties
    base.assists += current.assists;
    base.points += current.points;
  }

  return acc;
}, {}));
console.log(arrOut);

【讨论】:

    猜你喜欢
    • 2019-07-23
    • 1970-01-01
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 2016-12-31
    • 1970-01-01
    • 2014-12-27
    • 2018-05-13
    相关资源
    最近更新 更多