Undoubtedly, utilizing Object.keys()
is considered the most efficient method to retrieve an Object's keys. In case it is not supported in your environment, it can be easily replicated using a code snippet similar to the one in your example (with the exception that you must consider the fact that your loop will traverse through all properties in the prototype chain, unlike the behavior of Object.keys()
).
Nevertheless, the code snippet you provided...
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [];
for (var key in foo) {
keys.push(key);
}
See it in action on jsFiddle.
...can be optimized. You can directly assign the keys within the declaration of the variable.
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [], i = 0;
for (keys[i++] in foo) {}
View the revised version on jsFiddle.
Nevertheless, this behavior varies from what Object.keys()
actually does (jsFiddle). In such cases, you can simply refer to the shim provided in the MDN documentation.