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?
Yes, ECMAScript 5 defines
Object.keysto do this. (AlsoObject.getOwnPropertyNamesto 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).No, no built-in functionality for that, but it’s a fairly straightforward function to write:
Or building on
Object.keys(and using ES2015+ features, because I’m writing this part in late 2020):