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:
hasOwnProperty
is needed because it's possible to insert keys into the prototype object ofdictionary
. But you typically don't want those keys included in your list.For example, if you do this:
and then do a
for...in
loop overdictionary
, you'll geta
andb
, but you'll also getc
.