Loop through a 'Hashmap' in JavaScript

Viewed 116299

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?

9 Answers

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?

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.

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

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

Related