Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 305
user2374903 Avatar asked May 12 '13 13:05

user2374903


People also ask

Can I use forEach on a map in JavaScript?

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.

How do I iterate over a map using jquery?

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.)


1 Answers

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); } 
like image 112
David Schumann Avatar answered Sep 22 '22 04:09

David Schumann