Simon_Weaver Simon_Weaver - 1 month ago 8
Javascript Question

Getting a list of associative array keys

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"];

JW. JW.
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.

Comments