获取对象中属性的最大值

时间:2017-08-03 06:06:43

标签: javascript jquery json object

我试图获取对象中所有wins属性的最大值。这是一个缩短的对象示例,我试图获得wins的最大值,这将是11。

var coach_wins = {
  "player1": [
    {
      year: 2015,
      wins: 6
    },
    {
      year: 2016,
      wins: 6
    }
  ],
  "player2": [
    {
      year: 2015,
      wins: 11
    },
    {
      year: 2016,
      wins: 6
    }
  ]
};

目前我正在计算对象的长度,然后使用for循环遍历对象并获取密钥:

coach_wins[Object.keys(coach_wins)[i]];

然后再次执行此操作并存储每个胜利值的值;

有更有效的方法吗?

感谢。

7 个答案:

答案 0 :(得分:2)

var coach_wins = {
  "player1": [
    {
      year: 2015,
      wins: 6
    },
    {
      year: 2016,
      wins: 6
    }
  ],
  "player2": [
    {
      year: 2015,
      wins: 11
    },
    {
      year: 2016,
      wins: 6
    }
  ]
};

var max = Object.values(coach_wins) //get all the values of the object
  .reduce(function(largest, player){ //reduce the max for all player
    return player.reduce(function(largest, record){ //reduce the max for each player
      return (largest > record.wins ? largest : record.wins);
    }, largest);
  }, 0);

console.log(max);

答案 1 :(得分:0)

这个怎么样?

Object.values(coach_wins).reduce(
  (result, player) => Math.max(result, player.reduce(
    (wins, winsPerYear) => Math.max(wins, winsPerYear.wins)
  , 0))
, 0); // --> 11

答案 2 :(得分:0)

如果玩家的个别数组总是包含2,那我觉得很好但是如果它可以改变你可以去做这样的事情。一点代码但不会让你陷入异常

function getMaxWins(){
    var maxWins = 0;
    for (var curPlayer in coach_wins) {

        //checking whether is it contains records
        var playerRecords = coach_wins[curPlayer];

        if(playerRecords){
            playerRecords.forEach(function (playerRecord_) {
                if(maxWins < playerRecord_.wins) maxWins = playerRecord_.wins;
            });
        }
    }
    return maxWins;
}

console.log(getMaxWins());

答案 3 :(得分:0)

你可以试试这个..

var max = coach_wins[Object.keys(coach_wins)[0]][0].wins;
for (var player in coach_wins ) {
if (coach_wins.hasOwnProperty(player)) {
   var current_max = Math.max.apply(Math,coach_wins[player].map(function(o){return o.wins;}));
    max = current_max > max ? current_max:max;

        }
    }

答案 4 :(得分:0)

或者,使用功能方法和ES6语法,您可以

Math.max(...[].concat(...Object.values(coach_wins).map(p=>p.map(g=>g.wins))))

答案 5 :(得分:0)

如果/tmp的值大于变量,则可以将变量集定义为0,使用Object.values()迭代对象的值.forEach()以迭代每个数组,将变量设置为wins属性

的值

&#13;
&#13;
"wins"
&#13;
&#13;
&#13;

答案 6 :(得分:0)

预期的结果对象会受到赞赏,但我猜你正在寻找这个:

var result = {};

for(var player in coach_wins){
      result[player] = coach_wins[player].reduce((max, value) => {return value.wins>max?value.wins:max}, 0);
}