Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pick random property from a Javascript object

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;         }     }        } 
like image 909
Bemmu Avatar asked Mar 28 '10 07:03

Bemmu


People also ask

How do you use math random in JavaScript?

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.

How do you find the length of an object?

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.


2 Answers

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]]; }; 
like image 118
Lawrence Whiteside Avatar answered Sep 19 '22 20:09

Lawrence Whiteside


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; } 
like image 22
David Leonard Avatar answered Sep 22 '22 20:09

David Leonard