tags:

views:

98

answers:

2

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;
        }
    }       
}
+3  A: 

You can just build an array of key while walking through the object.

var keys = [];
for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        keys.push(prop);
    }
}

then randomly pick an element from the keys.

return keys[Math.floor(keys.length * Math.random())];
KennyTM
+5  A: 

Picking a random element from a stream

function pickRandomProperty(obj) {
    var result;
    var count = 0;
    for (var prop in obj)
        if (Math.random() < 1/++count)
           result = prop;
    return result;
}
David Leonard
excellent!.....
stereofrog
Does the ECMAScript standard say anything about the properties always being traversed in the same order? Objects in most implementations have stable ordering, but the behavior is undefined in the spec: http://stackoverflow.com/questions/280713/elements-order-for-in-loop-in-javascript/280861#280861
Brendan Berg