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
Most of the major browsers have this functionality built-in now, the method is Object.keys():
var keys = Object.keys(options);
//-> ["key1", "key2"]
You can also use a little snippet to implement this in browsers that don't support it:
Object.keys = Object.keys || (function () {
var hasOwnProperty = Object.prototype.hasOwnProperty;
return function (o) {
if (typeof o != "object" && typeof o != "function" || o === null)
throw new TypeError("Object.keys called on a non-object");
var result = [];
for (var name in o) {
if (hasOwnProperty.call(o, name))
result.push(name);
}
return result;
};
})();
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.