Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to loop randomly through the keys of an object?

Tags:

javascript

I have a for loop that looks something like

 for (var key in myObjectArray) {
   [code]
 }

I would like to do the same thing except have the order of the output shuffled every time.

Is there any easy way to do it? I can make a separate array of keys, sort them, and then do a for loop with an index… but that seems like a lot of work and rather inefficient.

like image 800
Dan Goodspeed Avatar asked Dec 14 '13 22:12

Dan Goodspeed


People also ask

Can you loop through an object?

The better way to loop through objects is first to convert the object into an array. Then, you loop through the array. You can convert an object into an array with three methods: Object.

Which loop is used to iterate over all the keys in an object?

The for...in loop will traverse all integer keys before traversing other keys, and in strictly increasing order, making the behavior of for...in close to normal array iteration.


1 Answers

Yes. First, you need an array of keys:

var keys;
if( Object.keys) keys = Object.keys(myObjectArray);
else keys = (function(obj) {var k, ret = []; for( k in obj) if( obj.hasOwnProperty(k)) ret.push(k); return ret;})(myObjectArray);
// isn't browser compatibility fun?

Next, shuffle your array.

keys.sort(function() {return Math.random()-0.5;});
// there are better shuffling algorithms out there. This works, but it's imperfect.

Finally, iterate through your array:

function doSomething(key) {
    console.log(key+": "+myObjectArray[key]);
}
if( keys.forEach) keys.forEach(doSomething);
else (function() {for( var i=0, l=keys.length; i<l; i++) doSomething(keys[i]);})();
like image 109
Niet the Dark Absol Avatar answered Sep 20 '22 05:09

Niet the Dark Absol