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.
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.
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.
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]);})();
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