Home > Net >  How do i choose a random nested property from an object in javascript?
How do i choose a random nested property from an object in javascript?

Time:09-17

Here's what i have at the moment:

let userTeams = ['Liverpool', 'Manchester City', 'Manchester United'];

let object = {
    teams: {
        'Liverpool': {
            player: 
            ['Salah',
            'Nunez']
        },
        'Manchester United': {
            player:
            ['Ronaldo',
            'Rashford']
        },
        'Manchester City': {
            player: 
            ['Haaland',
            'Foden']
        },
    },
};
let userTeam = userTeams[Math.floor(Math.random() * 3)];

I need the team selection to be directly but randomly from the object rather than from the userTeams array.

How would i go about that?

CodePudding user response:

I'm guessing that the OP really aims to get a random team name (key) and that team's data (value) in an object. Abstractly, in a few steps:

Here's how to get a random element from an array:

const randomElement = array => array[Math.floor(Math.random()*array.length)];

That can be used to get a random key from an object:

const randomKey = object => randomElement(Object.values(object));

And that can be used to get a random key-value pair:

const randomKeyValue = object => {
  const key = randomKey(object);
  return { [key] : object[key] };
};

All together:

let object = {
    teams: {
        'Liverpool': {
            player: 
            ['Salah',
            'Nunez']
        },
        'Manchester United': {
            player:
            ['Ronaldo',
            'Rashford']
        },
        'Manchester City': {
            player: 
            ['Haaland',
            'Foden']
        },
    },
};

const randomElement = array => array[Math.floor(Math.random() * array.length)];

const randomKey = object => randomElement(Object.keys(object));

const randomKeyValue = object => {
  const key = randomKey(object);
  return {
    [key]: object[key]
  };
};

console.log(randomKeyValue(object.teams))

CodePudding user response:

You can use random on the array which is the keys (or values) of object.teams

let object = {
  teams: {
    'Liverpool': {
      player: ['Salah',
        'Nunez'
      ]
    },
    'Manchester United': {
      player: ['Ronaldo',
        'Rashford'
      ]
    },
    'Manchester City': {
      player: ['Haaland',
        'Foden'
      ]
    },
  },
};
var teams = Object.values(object.teams);
let userTeam = teams[Math.floor(Math.random() * teams.length)];
console.log(userTeam);

  • Related