Get Random Property From A JavaScript Object

In this article, we will cover how to get random property from a JavaScript object. To achieve this, we need to create an array from the object keys using the `Object.keys()` method and then get a random value using the `random()` method from the `Math` object.

Then, we can use the `floor()` method from `Math` object to eliminate decimal values from the randomly generated number.

Then, we will return the key which matches to the index that is equal to the generated random number. To make sure the random number lies within the array indices; we need to multiply the randomly generated number by the length of the object keys array.

Get Random Property From A JavaScript Object

First, let’s create an object and initialize it with some values –

const obj = {

  key1: "value1",

  key2: "value2",

  key3: "value3",

  key4: "value4"

};

Then, we will create an array with the object keys using the `Object.keys()` method –

const keys = Object.keys(obj);

Now, we need to generate a random number using the `Math.floor()` to eliminate decimal point numbers and `Math.random()` to generate a random number. Then, we can multiply it with the `keys.length` to ensure the random number is within the array length.

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

We will pass this value to the `keys` array using the `[]` bracket notation to access the index of the array that corresponds to the random number and we will print the key that matches the index we get on the console.

console.log(keys[Math.floor(Math.random() * keys.length)]);
key4 gets printed on the console

As we can see, we got `key4` as our output which means that we got `3` as our random number.

Finally, we can wrap our logic into a function block so that we can use it on any object and return a random property from this object. We will call our function multiple times to check the different values we get each time.

const getRandomKey = (object) => {

const keys = Object.keys(object);

return keys[Math.floor(Math.random() * keys.length)];

};

console.log(getRandomKey(obj));

console.log(getRandomKey(obj));

console.log(getRandomKey(obj));

If we check our console, we can see that we got 3 different values that corresponds to keys inside our `keys` array.

3 different values corresponding to keys printed on the console

Leave a Reply