Javascript – Getting a list of associative array keys

arraysjavascript

I have an associative array in JavaScript:

var dictionary = {
    "cats": [1,2,3,4,5],
    "dogs": [6,7,8,9,10]
};

How do I get this dictionary's keys? I.e., I want

var keys = ["cats", "dogs"];

Just to get the terminology correct – there is no such thing as an 'associative array' in JavaScript – this is technically just an object and it is the object keys we want.

Best Answer

Try this:

var keys = [];
for (var key in dictionary) {
  if (dictionary.hasOwnProperty(key)) {
    keys.push(key);
  }
}

hasOwnProperty is needed because it's possible to insert keys into the prototype object of dictionary. But you typically don't want those keys included in your list.

For example, if you do this:

Object.prototype.c = 3;
var dictionary = {a: 1, b: 2};

and then do a for...in loop over dictionary, you'll get a and b, but you'll also get c.