Loop through a 'Hashmap' in JavaScript
Solution 1
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
"
Solution 2
for (var i = 0, keys = Object.keys(a_hashmap), ii = keys.length; i < ii; i++) {
console.log('key : ' + keys[i] + ' val : ' + a_hashmap[keys[i]]);
}
Solution 3
You can use JQuery function
$.each( hashMap, function(index,value){
console.log("Index = " + index + " value = " + value);
})
Solution 4
Do you mean
for (var i in a_hashmap) { // Or `let` if you're a language pedant :-)
...
}
i
is undefined when the for-loop gets set up.
Solution 5
Try this in order to print console correctly...
for(var i in a_hashMap) {
if (a_hashMap.hasOwnProperty(i)) {
console.log('Key is: ' + i + '. Value is: ' + a_hashMap[i]);
}
}
Related videos on Youtube
myol
Updated on September 26, 2022Comments
-
myol almost 2 years
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?
-
elvenbyte almost 13 yearsJust watch this thread: [Javascript Hashmap Equivalent][1] Hope it helps you. [1]: stackoverflow.com/questions/368280/…
-
-
spraff almost 13 yearsDidn't think to check. I suppose you're right.
-
spraff almost 13 yearsDownvote?
let
aside, this is the same as the accepted answer :-/ -
Nivas almost 13 years+1 because this does not deserve a -1. @spraff, you might want to add an update (edit the answer) stating what you have stated in comments.
-
abhy about 7 yearsThis is neat way to loop through keys and values.
-
SJ00 over 6 years+1 for mentioning 'let'. This is best use case of let. Anyone down voting, probably ignored the fact, JS is used on servers as well.