Iterate Through A Map In Javascript
Solution 1:
An answer to your Question from 2019:
It depends on what version of ECMAScript you use.
Pre ES6:
Use any of the answers below, e.g.:
for (var m in myMap){
for (var i=0;i<myMap[m].length;i++){
... do something with myMap[m][i] ...
}
}
For ES6 (ES 2015):
You should use a Map
object, which has the entries()
function:
var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
for (const [key, value] of myMap.entries()) {
console.log(key, value);
}
For ES8 (ES 2017):
Map.prototype.entries()
was introduced:
const mapOne = newMap([['a', 1], ['b', 2], ['c' , 3]]);
for (const [key, value] of mapOne.entries()) {
console.log(key, value);
}
Solution 2:
I'd use standard javascript:
for (var m in myMap){
for (var i=0;i<myMap[m].length;i++){
... do something with myMap[m][i] ...
}
}
Note the different ways of treating objects and arrays.
Solution 3:
Functional Approach for ES6+
If you want to take a more functional approach to iterating over the Map
object, you can do something like this
const myMap = newMap()
myMap.forEach((value, key) => {
console.log(value, key)
})
Solution 4:
The callback to $.each()
is passed the property name and the value, in that order. You're therefore trying to iterate over the property names in the inner call to $.each()
. I think you want:
$.each(myMap, function (i, val) {
$.each(val, function(innerKey, innerValue) {
// ...
});
});
In the inner loop, given an object like your map, the values are arrays. That's OK, but note that the "innerKey" values will all be numbers.
edit — Now once that's straightened out, here's the next problem:
setTimeout(function () {
// ...
}, i * 6000);
The first time through that loop, "i" will be the string "partnr1". Thus, that multiplication attempt will result in a NaN
. You can keep an external counter to keep track of the property count of the outer map:
var pcount = 1;
$.each(myMap, function(i, val) {
$.each(val, function(innerKey, innerValue) {
setTimeout(function() {
// ...
}, pcount++ * 6000);
});
});
Solution 5:
Well, it looks like this old JQuery thread has been coopted by ES6 Map users.
If this is what you're looking for, may I suggest using the Array.from()
function which converts the Map
to an Array
. This allows you to easily chain transforms such as filter()
, map()
, etc.
const map = newMap([
['key one', 'value one'],
['key two', 'value two'],
]);
// Loop through key-value-pairsArray.from(map.entries()).map(([key, val]) =>console.log(key, val));
// Loop through map keysArray.from(map.keys()).map(key =>console.log(key));
// Loop through valuesArray.from(map.values()).map(value =>console.log(value));
Post a Comment for "Iterate Through A Map In Javascript"