I was wondering if there was a quick way to extract keys of associative array into an array, or comma-separated list using JavaScript (jQuery is ok).
options = {key1: "value1", key2: "value2"};
Result should be the array:
["key1", "key2"]
or just a string:
"key1, key2"
Most of the major browsers have this functionality built-in now, the method is
Object.keys()
:You can also use a little snippet to implement this in browsers that don't support it:
That snippet works much the same as the one in Nick Craver's example with 2 exceptions:
hasOwnProperty
method.This (and the other answers here) doesn't work around an IE enumeration bug, however. You can find more information and a partial work around for that on this answer here.
A jQuery way of doing it:
You can use
$.each()
in jQuery:then
gives you
["key1", "key2"]
as an array, which you couldjoin
to get a string.You can easily get an array of them via a
for
loop, for example:Then use
keys
how you want, for example:You can test it out here. The
.hasOwnProperty()
check is to be safe, in case anyone messed with the object prototype and such.You can now use
to get an array consisting of the available keys in an object. Mozilla has usage and availability information.