46

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?

myol
  • 8,857
  • 19
  • 82
  • 143
  • 1
    Just watch this thread: [Javascript Hashmap Equivalent][1] Hope it helps you. [1]: http://stackoverflow.com/questions/368280/javascript-hashmap-equivalent – elvenbyte Jul 19 '11 at 14:35

10 Answers10

63
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"

jhurshman
  • 5,861
  • 2
  • 26
  • 16
12
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]]);
}
Raynos
  • 166,823
  • 56
  • 351
  • 396
7

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.

spraff
  • 32,570
  • 22
  • 121
  • 229
  • Didn't think [to check](http://en.wikipedia.org/wiki/JavaScript#Versions). I suppose you're right. – spraff Jul 19 '11 at 14:34
  • Downvote? `let` aside, this is the same as the accepted answer :-/ – spraff Jul 19 '11 at 15:28
  • +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. – Nivas Jul 19 '11 at 15:37
  • +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. – SJ00 Dec 08 '17 at 11:47
7

You can use JQuery function

$.each( hashMap, function(index,value){
 console.log("Index = " + index + " value = " + value); 
})
GothamGirl
  • 299
  • 1
  • 2
  • 15
dchhetri
  • 6,926
  • 4
  • 43
  • 56
6

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]);
    }
}
Atmaram
  • 152
  • 3
  • 11
4

Iterating through a map in vanilla Javacsript is simple .

var map = {...};//your map defined here
for(var index in map)
 {
       var mapKey = index;//This is the map's key.
       for(i = 0 ; i < map[mapKey].length ; i++)
        {
              var mapKeyVal = map[mapKey];//This is the value part for the map's key.


          }
  }
Binita Bharati
  • 5,239
  • 1
  • 43
  • 24
2

This is an old post, but one way I can think of is

const someMap = { a: 1, b: 2, c: 3 };
Object.keys(someMap)
.map(key => 'key is ' + key + ' value is ' + someMap[key]);

Should this way of iterating be used? Are there any issues with this approach?

Ketu
  • 1,608
  • 2
  • 14
  • 30
1

For lopping through a Hashmap you need to fetch the keys and values.

const new_Map = new Map();

for (const [key, value] of new_Map.entries()) {
   console.log(`The key is ${key} and value is ${value}`);
}

It should work with keys and values of hashmap in key and value.

Khushal Vyas
  • 316
  • 3
  • 8
1

var a_hashMap = {a:1,b:2,c:3};

for (var key in a_hashMap) {
    console.log('Key: ' + key + '. Value: ' + a_hashMap[key]);
}
Matt
  • 33,328
  • 25
  • 83
  • 97
0

many of the answer are using for-in but it didn't work for me in nodejs. there are below methods which you can use to iterate over the Hashmap. Injavascript hashmap store key-value pair in series so what key-value stored first will come first and last will come in the last when iterating

let map = new Map();
map.set(2,"two");
map.set(1,"one");
map.set(3,"three");

// in this map when you iterate keys will will in order 2,1,3

below methods will work in iteration of a Hashmap

// iterate by using keys of map

let map = new Map();
map.set(1,true);
map.set(2,false);
map.set(3,true);
map.set(4,true);

let keys = map.keys();

    for(let key of keys) console.log(`for key ${key} the value is : ${map.get(key)}`)

// to print value only without key

     let map = new Map();
     map.set(1,"one");
     map.set(2,"two");
     map.set(3,"three");
 
     for(let value of map.values()) console.log(`value is ${value}`)

 // by usign key value pairs using entries 

    let map = new Map();
    map.set(1,true);
    map.set(2,false);
    map.set(3,true);
    map.set(4,true);
    // Object.entries() return a array of pair and pair is array of key and value
    for(let pair of map.entries()) console.log(`for key ${pair[0]} the value is ${pair[1]}`)
    /* you can use [key,value] insted of pair by destructuring pair*/

// by using forEach for keys and value

      let map = new Map();
      map.set(1,true);
      map.set(2,false);
      map.set(3,true);
      map.set(4,true);
      
      map.forEach((val,key)=>{ console.log(`for the key ${key} the value is ${val}`)})
 
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 03 '23 at 10:32