iterate through a map in javascript
I have a structure like this:
var myMap = {
partnr1: ['modelA', 'modelB', 'modelC'],
partnr2: ['modelA', 'modelB', 'modelC']
};
I am going to iterate through each of the elements (partnr) with their associatives (models).
I am trying a double $each iteration in order to achieve this, but nothing happens:
$.each(myMap, function (i, val) {
$.each(i, function (innerKey, innerValue) {
setTimeout(function () {
$('#variant').fadeOut("slow", function () {
$(this).text(innerKey + "-" + innerValue).fadeIn("slow");
});
}, i * 6000);
});
});
The effect with fading in and out that I am trying to achieve is working fine when using a single value array (Object), but not when I need to have more than one value for each key like here.
Any ideas of how to accomplish this iteration succesfully and are there other ways than using a map that would be better in this case ?
Any suggestions would be of interest.
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):
Object.entries()
was introduced:
const object = {'a': 1, 'b': 2, 'c' : 3};
for (const [key, value] of Object.entries(object)) {
console.log(key, value);
}
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.
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 = new Map()
myMap.forEach((value, key) => {
console.log(value, key)
})