Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
136
rated 0 times [  140] [ 4]  / answers: 1 / hits: 29849  / 12 Years ago, thu, july 19, 2012, 12:00:00

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?


More From » regex

 Answers
20

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));
}

[#84148] Wednesday, July 18, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
davisbrandtm

Total Points: 387
Total Questions: 99
Total Answers: 106

Location: Tuvalu
Member since Sat, Feb 11, 2023
1 Year ago
;