23

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"
4
  • 2
    I think you meant ["key1","key2"] not {"key1","key2"} Commented Dec 9, 2010 at 15:48
  • possible duplicate of How to list the properties of a javascript object Commented Dec 9, 2010 at 16:04
  • It is. Too bad array is never mentioned there. Commented Dec 9, 2010 at 16:20
  • 3
    That's because there's no such thing as an associative array in JavaScript. What you call an associative array is an object with a list of properties (hence, how to list the properties of a javascript object). That's also why the native method to list the keys resides on the Object object - Object.keys(). Commented Dec 9, 2010 at 16:39

6 Answers 6

31

You can easily get an array of them via a for loop, for example:

var keys = [];
for(var key in options) {
  if(options.hasOwnProperty(key)) { //to be safe
    keys.push(key);
  }
}

Then use keys how you want, for example:

var keyString = keys.join(", ");

You can test it out here. The .hasOwnProperty() check is to be safe, in case anyone messed with the object prototype and such.

Sign up to request clarification or add additional context in comments.

Comments

30
options = {key1: "value1", key2: "value2"};
keys = Object.keys(options);

2 Comments

Please note that this is not supported by IE8 and below, currently 7.3% of worldwide browsers.
IE8 and below are now now about 1% of worldwide browsers.
5

A jQuery way of doing it:

var keys = [];
options = {key1: "value1", key2: "value2"};
$.each(options, function(key, value) { keys.push(key) })
console.log(keys)

1 Comment

you can also use keys[keys.length] = key; to be IE safe
3

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:

  • It will throw a meaningful TypeError if you pass anything other than an Object in (or "associative array", if you like).
  • It will work around an annoying DOM-related issue in Internet Explorer where collections don't have the 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.

Comments

2

You can now use

Object.keys(obj)

to get an array consisting of the available keys in an object. Mozilla has usage and availability information.

Comments

0

You can use $.each() in jQuery:

function keyArray(obj) {
  var rv = [];
  $.each(options, function(key) { rv.push(key); });
  return rv;
}

then

var keys = keyArray(options);

gives you ["key1", "key2"] as an array, which you could join to get a string.

3 Comments

The reason I don't advocate doing it this way is it's not safe, for example if anything's on the prototype, it'll appear in the list as well. jQuery doesn't do a hasOwnProperty() check internally, see what I mean here: jsfiddle.net/nick_craver/TJDCV
oh well that's a good point - personally the lack of functional tools like that (that work "right") is the thing I miss most about Prototype, and I acknowledge that those things in Prototype are also the source of its biggest problems :-)
I guess that if there were a solid utility to convert an object to an array of key/value pairs (as 2-element arrays), plus a .zip() function, you could go a long way ...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.