Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through a 'Hashmap' in JavaScript

I'm using this method to make artificial 'hashmaps' in javascript. All I am aiming for is key|value pairs, the actual run time is not important. The method below works fine.

Are there any other ways to loop through this?

for (var i in a_hashMap[i]) {     console.log('Key is: ' + i + '. Value is: ' + a_hashMap[i]); }  

I run into a problem where this outputs a bunch of undefined keys after the first key, when the array only contains one entry. I have a feeling it is because the code is within a loop which uses i, even though when I follow in debug it shouldn't be happening. I also cannot change i as the for loop seems to not understand the replaced var at all.

Anyone any ideas?

like image 811
myol Avatar asked Jul 19 '11 14:07

myol


People also ask

How do I iterate through a Map in JavaScript?

Iterate through a Map using JavaScript # Use the forEach() method to iterate over a Map object. The forEach method takes a function that gets invoked for each key/value pair in the Map , in insertion order. The function gets passed the value, key and the Map object on each iteration.

Is there a Hashmap in JavaScript?

While JavaScript doesn't have a native Hashtable class, it does have native Objects and Hashmaps(Map) that offer similar functionality when it comes to organizing key/value pairs.


1 Answers

for (var i in a_hashmap[i]) 

is not correct. It should be

for (var i in a_hashmap) 

which means "loop over the properties of a_hashmap, assigning each property name in turn to i"

like image 175
jhurshman Avatar answered Oct 01 '22 04:10

jhurshman