Is there a way to cycle through the keys of an object?

I have a for loop that looks something like

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

I would like to do the same, except that each time they will move in order.

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

+4
source share
1 answer

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?

Then shuffle your array.

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

Finally, iterate through the 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]);})();
+7
source

All Articles