如何从JSON获取最大值并显示相关数据(API/Javascript)?

const input = {
  "elements": [{
      "first_name": "Petr",
      "second_name": "Cech",
      "minutes": 585,
      "goals_scored": 0,
      "assists": 0,
      "clean_sheets": 1,
    },
    {
      "first_name": "Bernd",
      "second_name": "Leno",
      "minutes": 135,
      "goals_scored": 0,
      "assists": 0,
      "clean_sheets": 0,
    },
    {
      "first_name": "Mesut",
      "second_name": "Özil",
      "minutes": 510,
      "goals_scored": 2,
      "assists": 0,
      "clean_sheets": 2,
    }
  ]
};

const stats = input.elements.reduce((stats, player) => {
  ['minutes', 'goals_scored', 'assists', 'clean_sheets'].forEach(key => {
    if (player[key] > stats[key].max) {
      stats[key].max = player[key];
      stats[key].bestPlayer = player;
    }
  });
  return stats;
}, {
  minutes: {max: 0, bestPlayer: null}, 
  goals_scored: {max: 0, bestPlayer: null}, 
  assists: {max: 0, bestPlayer: null}, 
  clean_sheets: {max: 0, bestPlayer: null}
});

console.log('minutes', stats.minutes);
console.log('goals_scored', stats.goals_scored);
console.log('assists', stats.assists);
console.log('clean_sheets', stats.clean_sheets);

文章来源:https://cloud.tencent.com/developer/ask/195650复制代码

转载于:https://juejin.im/post/5ca99c0b6fb9a05e202223b1

你可能感兴趣的:(如何从JSON获取最大值并显示相关数据(API/Javascript)?)