"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Efficiently Select a Random Property from a JavaScript Object?

How to Efficiently Select a Random Property from a JavaScript Object?

Published on 2024-11-06
Browse:644

How to Efficiently Select a Random Property from a JavaScript Object?

Selecting a Random Property from a JavaScript Object

Fetching a random property from a JavaScript object is a fundamental task that can arise in various coding scenarios. Consider an object containing key-value pairs like:

{cat: 'meow', dog: 'woof', snake: 'hiss'}

Traditionally, this task could be accomplished through a lengthy loop that iterates through the object's properties, randomly selects one, and retrieves its value. However, this approach can be verbose and computationally inefficient.

An Optimized Solution

A more concise and efficient solution for selecting a random property from an object is provided by the following code:

var randomProperty = function (obj) {
    var keys = Object.keys(obj);
    return obj[keys[ keys.length * Math.random() << 0]];
};

This code employs the following steps:

  1. Retrieves all property keys of the object using Object.keys(), resulting in an array of keys.
  2. Generates a random index within the range of array indices using Math.random().
  3. Accesses the property at the calculated index using the bracket notation operator [ ].

This solution avoids the need for loops and directly fetches the random property, making it both concise and computationally faster.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3