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 fi
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]]);
}
You can use JQuery function
$.each( hashMap, function(index,value){
console.log("Index = " + index + " value = " + value);
})
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.
}
}
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?
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.
Hash maps can be tricky, but quite useful. When iterating over one as you would an object, each key is a tuple with [key, value]:
for (let key of map) {
console.log('Key is: ' + key[0] + '. Value is: ' + key[1]);
}