iterate through a map in javascript

后端 未结 5 1590
温柔的废话
温柔的废话 2021-02-01 13:13

I have a structure like this:

var myMap = {
    partnr1: [\'modelA\', \'modelB\', \'modelC\'],
    partnr2: [\'modelA\', \'modelB\', \'modelC\']
};
5条回答
  •  别那么骄傲
    2021-02-01 13:58

    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

    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);
    }
    

提交回复
热议问题