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.
The Map. forEach method is used to loop over the map with the given function and executes the given function over each key-value pair.
The $. each() function can be used to iterate over any collection, whether it is a map (JavaScript object) or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time. (The value can also be accessed through the this keyword.)
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With