Pick random property from a Javascript object

Posted by Bemmu on Stack Overflow See other posts from Stack Overflow or by Bemmu
Published on 2010-03-28T07:40:06Z Indexed on 2010/03/28 7:43 UTC
Read the original article Hit count: 273

Filed under:

Suppose you have a Javascript object like {'cat':'meow','dog':'woof' ...} Is there a more concise way to pick a random property from the object than this long winded way I came up with:

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;
        }
    }       
}

© Stack Overflow or respective owner

Related posts about JavaScript