Simon_Weaver Simon_Weaver - 1 year ago 98
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"];

Answer Source

Try this:

var keys = [];
for (var key in dictionary) {
  if (dictionary.hasOwnProperty(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 loop over dictionary, you'll get a and b, but you'll also get c.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download