Home >Web Front-end >JS Tutorial >How to Efficiently Retrieve a Random Property from a JavaScript Object?

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 01:07:02922browse

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

Retrieving a Random Object Property with Enhanced Efficiency

Suppose you encounter an object in Javascript that resembles this:

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

You may wish to obtain a random property from this object. Instead of employing a protracted method like the one below:

function pickRandomProperty(obj) {
    var prop, len = 0, randomPos, pos = 0;
    for (prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            len += 1;
        }
    }
    randomPos = Math.floor(Math.random() * len);
    for (prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            if (pos === randomPos) {
                return prop;
            }
            pos += 1;
        }
    }       
}

Consider leveraging this optimized approach:

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

This technique optimizes performance enhancements by leveraging the Object.keys() method to retrieve an array of the object's keys. Subsequently, it employs the array's length multiplied by a random number to obtain an index for the array to retrieve the key. Finally, it accesses the corresponding property in the object to return the desired random property.

The above is the detailed content of How to Efficiently Retrieve a Random Property from a JavaScript Object?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn