Search code examples
javascript-objectsdestructuring

Get a value from an object using a variable as a key


I have an Object like;

  players: {
    '1': {id:1, name:'', ....},
    '2': {id:2, name:'', ....},
     ... 
   }

I want to desctruct an object by its key as currentPlayer. (playernumber is passed as props).

const currentPlayer = Object.keys(players).filter(
      obj => obj.id === playerNumber
    );

this did not work, also I do not want to use id attribute.


Solution

  • The easiest way to get a specific player is with bracket notation:

    const currentPlayer = players[playerNumber];
    

    This assumes that playerNumber is a valid key in the players object.