views:

3431

answers:

3

I have an associative array in JSON

var dictionary = {"cats":[1,2,37,38,40,32,33,35,39,36], "dogs", [4,5,6,3,2]};

Can I get the keys from this? I tried in Visual studio putting a breakpoint but can't see any property that represents keys. Is it not possible?

I'm fine creating a separate array if necessary, but was just hoping it wasnt :

var keys = ["cats", "dogs"];
+3  A: 

Try this:

var keys = [];
for (var key in dictionary) {
  if (dictionary.hasOwnProperty(key)) {
    keys.push(key);
  }
}
JW
+3  A: 
for (var key in dictionary) {
  // do something with key
}

It's the for..in statement.

wombleton
thanks. wasn't getting anywhere trying a regular for loop
Simon_Weaver
Just noticed that there should be a colon instead of a comma between "dogs" and the array above. Assume it's due to transcription.
wombleton
+2  A: 

Just a quick note, be wary of using for..in if you use a library (jQuery, prototype, etc.), as most of them add methods to created Objects (including dictionaries).

This will mean that when you loop over them, method names will appear as keys. If you are using a library, look at the documentation and look for an enumerable section, where you will find the right methods for iteration of your objects.

Jesse