Loop through a 'Hashmap' in JavaScript

112,045

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]);
    }
}
Share:
112,045

Related videos on Youtube

myol
Author by

myol

Updated on September 26, 2022

Comments

  • myol
    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?

  • spraff
    spraff almost 13 years
    Didn't think to check. I suppose you're right.
  • spraff
    spraff almost 13 years
    Downvote? let aside, this is the same as the accepted answer :-/
  • Nivas
    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
    abhy about 7 years
    This is neat way to loop through keys and values.
  • SJ00
    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.