I would like to get the keys of a JavaScript object as an array, either in jQuery or pure JavaScript.
Is there a less verbose way than this?
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [];
for (var key in foo) {
keys.push(key);
}
Summary
For getting all of the keys of an Object you can use
Object.keys()
.Object.keys()
takes an object as an argument and returns an array of all the keys.Example:
In the above example we store an array of keys in the keys const. We then can easily access the amount of properties on the object by checking the length of the keys array.
Getting the values with:
Object.values()
The complementary function of
Object.keys()
isObject.values()
. This function takes an object as an argument and returns an array of values. For example:Use
Object.keys
.This is an ES5 feature. This means it works in all modern browsers but will not work in legacy browsers.
The ES5-shim has a implementation of
Object.keys
you can stealOf course,
Object.keys()
is the best way to get an Object's keys. If it's not available in your environment, it can be trivially shimmed using code such as in your example (except you'd need to take into account your loop will iterate over all properties up the prototype chain, unlikeObject.keys()
's behaviour).However, your example code...
jsFiddle.
...could be modified. You can do the assignment right in the variable part.
jsFiddle.
Of course, this behaviour is different to what
Object.keys()
actually does (jsFiddle). You could simply use the shim on the MDN documentation.You can use jQuery's
$.map
.I don't know about less verbose but I was inspired to coerce the following onto one line by the one-liner request, don't know how Pythonic it is though ;)