48

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?

1

10 Answers 10

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

Sign up to request clarification or add additional context in comments.

Comments

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]]);
}

1 Comment

This is neat way to loop through keys and values.
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.

4 Comments

Didn't think to check. I suppose you're right.
Downvote? let aside, this is the same as the accepted answer :-/
+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.
+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.
7

You can use JQuery function

$.each( hashMap, function(index,value){
 console.log("Index = " + index + " value = " + value); 
})

Comments

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]);
    }
}

Comments

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.


          }
  }

Comments

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?

Comments

2

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

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

Comments

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.

Comments

1

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}`)})
 

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.