What is the best way to loop through this Object?

Michal K :

I'm stuck at looping through a Object called Players that contains player data. I want to check which player have the highest x value and save it in leader variable that will changes while an other player have higher x value.

The Object looks like this:

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'  
  }
}

This is how I want my output to look like

leader = GZPYpWdrzj9x0;
Jay Vaghasiya :

Please use 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);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31909&siteId=1