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); }
To convert an array's values to object keys:Declare a new variable and set it to an empty object. Use the forEach() method to iterate over the array. On each iteration, assign the array's element as a key in the object.
The object contains keys and values. To access the object's keys, use the keys() method. For example, the keys() method in JavaScript is used to return a simple array's enumerable properties.
Use Object.keys
:
var foo = { 'alpha': 'puffin', 'beta': 'beagle' }; var keys = Object.keys(foo); console.log(keys) // ['alpha', 'beta'] // (or maybe some other order, keys are unordered).
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 steal
You can use jQuery's $.map
.
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' }, keys = $.map(foo, function(v, i){ return 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