首页 > 解决方案 > 遍历此对象的最佳方法是什么?

问题描述

我被困在循环一个名为Players包含玩家数据的对象中。我想检查哪个玩家的x价值最高,并将其保存在leader变量中,该变量会在其他玩家具有更高的x价值时发生变化。

对象如下所示:

var players = {
  '86wjIB7Xbz1tmwlTAAAB': {
     rotation: 0.09999999999999964,    
     x: 579,
     y: 579,
     playerId: '86wjIB7Xbz1tmwlTAAAB'  
   },
  'dWwtnOI8PryXJNDWAAAC': {
    rotation: 0.09999999999999964,    
    x: 488,
    y: 579,
    playerId: 'dWwtnOI8PryXJNDWAAAC'  
  },
 'GZPYpWdrzj9x0-SsAAAD': {
    rotation: -0.09999999999999964,   
    x: 694,
    y: 579,
    playerId: 'GZPYpWdrzj9x0-SsAAAD'  
  }
}

这就是我希望输出的样子

leader = GZPYpWdrzj9x0;

标签: javascriptloopsobject

解决方案


请使用 Object.keys

var players = {
    '86wjIB7Xbz1tmwlTAAAB': {
      rotation: 0.09999999999999964,    
      x: 579,
      y: 579,
      playerId: '86wjIB7Xbz1tmwlTAAAB'  
    },
    dWwtnOI8PryXJNDWAAAC: {
      rotation: 0.09999999999999964,    
      x: 488,
      y: 579,
      playerId: 'dWwtnOI8PryXJNDWAAAC'  
    },
    'GZPYpWdrzj9x0-SsAAAD': {
      rotation: -0.09999999999999964,   
      x: 694,
      y: 579,
      playerId: 'GZPYpWdrzj9x0-SsAAAD'  
    }
  }

  const leader = Object.keys(players).reduce((acc, cur) => {
    const obj = players[cur];
    return acc.x < obj.x ? { x:obj.x, leader: obj.playerId } : acc;
  }, { x: 0, leader: "" });

  console.log(leader);


推荐阅读