如何通过密钥对JSON数组进行分组?

时间:2018-02-25 08:35:27

标签: javascript jquery json

我有一组包含游戏数据的对象。数组中的每个对象都有日期,位置,游戏类型,赢家和输家。

我希望我的输出是一个具有属性player,wins和loss的对象数组(即输出将按玩家分组,而数组输入中的每个对象都有一个赢家玩家和一个输家玩家)。输出将告诉我,在所有比赛中,每位球员有多少输赢。

1 个答案:

答案 0 :(得分:0)

我假设您的游戏数据结构如下

const gameData = [{
  date: '12/02/2018',
  location: 'Germany',
  gameType: 'any',
  winner: 'Joe Smith',
  loser: 'Leo Messi',
}, {
  date: '20/02/2018',
  location: 'Australia',
  gameType: 'any',
  winner: 'Joe Smith',
  loser: 'Cristiano',
}, {
  date: '23/02/2018',
  location: 'England',
  gameType: 'any',
  winner: 'Alexi Sanchez',
  loser: 'Joe Smith',
}]

然后这是可能的解决方案。

const gameData = [{
  date: '12/02/2018',
  location: 'Germany',
  gameType: 'any',
  winner: 'Joe Smith',
  loser: 'Leo Messi',
}, {
  date: '20/02/2018',
  location: 'Australia',
  gameType: 'any',
  winner: 'Joe Smith',
  loser: 'Cristiano',
}, {
  date: '23/02/2018',
  location: 'England',
  gameType: 'any',
  winner: 'Alexi Sanchez',
  loser: 'Joe Smith',
}]

const playerObjects = gameData.reduce((acc, game) => {
  if (acc[game.winner]) {
    acc[game.winner].wins = acc[game.winner].wins + 1 || 1;
  } else acc[game.winner] = { wins: 1, loses: 0};
  if(acc[game.loser]){
    acc[game.loser].loses = acc[game.loser]['loses'] + 1 || 1;
  } else acc[game.loser] = { wins: 0, loses: 1};
  return acc;
}, {});

const results = Object.keys(playerObjects).reduce((arr, key) => {
  const player = {
   name: key,
   wins: playerObjects[key].wins,
   loses: playerObjects[key].loses,
  };
  arr.push(player);
  return arr;
}, []);

console.log(results);