Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript :: How to get keys of associative array to array variable?

Let's have an associative array like this:

var aArray = {};
aArray.id = 'test';
aArray['x1'] = [1,2,3];
aArray['stackoverflow'] = 'What\'s up?';
aArray['x2'] = [4,5,6];
var keys = [];
for(var key in aArray) {
  if (aArray.hasOwnProperty(key)) {
    keys.push(key);
  }
}
console.log(keys);

Is there any easy/short way how to get array of keys to array variable without loop?

If so, additionally, is possible to apply some regular expression to key list to get just keys that match such pattern (let's say /^x/) without another loop?

like image 229
Ωmega Avatar asked Jul 19 '12 12:07

Ωmega


2 Answers

Is there any easy/short way how to get array of keys to array variable without loop..?

Yes, ECMAScript 5 defines Object.keys to do this. (Also Object.getOwnPropertyNames to get even the non-enumerable ones.) Most moderns browser engines will probably have it, older ones won't, but it's easily shimmed (for instance, this shim does).

If so, additionally, is possible to apply some regular expression to key list to get just keys that match such pattern (let's say /^x/) without (another) loop?

No, no built-in functionality for that, but it's a fairly straightforward function to write:

function getKeys(obj, filter) {
    var name,
        result = [];

    for (name in obj) {
        if ((!filter || filter.test(name)) && obj.hasOwnProperty(name)) {
            result[result.length] = name;
        }
    }
    return result;
}

Or building on Object.keys (and using ES2015+ features, because I'm writing this part in late 2020):

function getKeys(obj, filter) {
    const keys = Object.keys(obj);
    return !filter ? keys : keys.filter(key => filter.test(key) && obj.hasOwnProperty(key));
}
like image 115
T.J. Crowder Avatar answered Nov 09 '22 04:11

T.J. Crowder


In the year 2020, every browser supports this back to IE9. This is the way to go.

JavaScript 1.8.5 has this functionality built in with Object.keys(). It returns an array of all of the keys. You could use a shim for non-supported browsers (MDN has help on that too).

As an example see this (jsFiddle)...

var obj = { "cat" : "meow", "dog" : "woof"};
alert(Object.keys(obj)); // "cat,dog"
like image 34
scottheckel Avatar answered Nov 09 '22 05:11

scottheckel