Given a dictionary-like object in Javascript such as {a:1, b:-2, c:42}
, is there a simple way to randomly choose a property?
In the above example, I would like to have a function that would return a
, b
or c
randomly.
The solution I've come up with is like the following:
var proplist = []
forEach(property in foo) {
if(propertyIsEnumerable(foo[property]) {
proplist.push(property);
}
}
var n = proplist.length;
// randomly choose property (randInt(n) returns a random integer in [0,n))
proplist[randInt(n)];
Is there a more idiomatic way to do this?