Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get array of object's keys

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); } 
like image 430
Richard Avatar asked Jan 06 '12 19:01

Richard


People also ask

How do you get the keys of an array of objects?

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.

How do you access a key inside of an object inside of an array JavaScript?

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.


2 Answers

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

like image 143
Raynos Avatar answered Oct 21 '22 17:10

Raynos


You can use jQuery's $.map.

var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' }, keys = $.map(foo, function(v, i){   return i; }); 
like image 32
Rocket Hazmat Avatar answered Oct 21 '22 15:10

Rocket Hazmat