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; } } }
In JavaScript, to get a random number between 0 and 1, use the Math. random() function. If you want a random number between 1 and 10, multiply the results of Math. random by 10, then round up or down.
You can simply use the Object. keys() method along with the length property to get the length of a JavaScript object. The Object. keys() method returns an array of a given object's own enumerable property names, and the length property returns the number of elements in that array.
The chosen answer will work well. However, this answer will run faster:
var randomProperty = function (obj) { var keys = Object.keys(obj); return obj[keys[ keys.length * Math.random() << 0]]; };
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With