Categories
JavaScript Answers

How to Pick a Random Property from a JavaScript Object?

Spread the love

To pick a random property from a JavaScript object, we can use the Object.keys method to get the keys of the object in an array.

Then we can use the Math.random and Math.floor methods to get a random index in the keys array.

For instance, we can write:

const animals = {
  'cat': 'meow',
  'dog': 'woof',
  'cow': 'moo',
  'sheep': 'baaah',
  'bird': 'tweet'
};

const keys = Object.keys(animals)
const prop = keys[Math.floor(Math.random() * keys.length)]
console.log(prop);

We have the animals object that we want to get a random key from.

Then we get the keys with the Object.keys method.

Next, we get a random array index of in keys with:

Math.floor(Math.random() * keys.length)

And we pass that into the square brackets to get the key from animals .

If we want to get the values, we just replace Object.keys with Object.values by writing:

const animals = {
  'cat': 'meow',
  'dog': 'woof',
  'cow': 'moo',
  'sheep': 'baaah',
  'bird': 'tweet'
};

const values = Object.values(animals)
const prop = values[Math.floor(Math.random() * values.length)]
console.log(prop);

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to Pick a Random Property from a JavaScript Object?”

Leave a Reply

Your email address will not be published. Required fields are marked *