13

Possible Duplicate:
Loop through JavaScript object
Get array of object’s keys

Is there a way to use hashmaps in javascript. I found this page which shows one way of having hashmaps in javascript. Based on that I am storing the data as below:

var map = new Object();
map[myKey1] = myObj1;
map[myKey2] = myObj2;

function get(k) {
   return map[k];
}

But I want the keySet (all the keys) of the map object just like it is done in Java (map.keySet();).

Can anyone show me how can get all the keys present in this object?

Community
  • 1
  • 1
DarkKnightFan
  • 1,913
  • 14
  • 42
  • 61

2 Answers2

16
for (var key in map) {
  if (map.hasOwnProperty(key)) {
    alert(key + " -> " + map[key]);
  }
}

https://stackoverflow.com/a/684692/106261

actually this way is much better :

var keys = Object.keys(map);
Community
  • 1
  • 1
NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
-2

You can use for..in statement:

for (var key  in map) {
    return map[key];
}
AlexR
  • 114,158
  • 16
  • 130
  • 208