Iterating over Typescript Map

前端 未结 12 1697
无人共我
无人共我 2020-12-07 16:26

I\'m trying to iterate over a typescript map but I keep getting errors and I could not find any solution yet for such a trivial problem.

My code is:

         


        
相关标签:
12条回答
  • 2020-12-07 16:53

    I'm using latest TS and node (v2.6 and v8.9 respectively) and I can do:

    let myMap = new Map<string, boolean>();
    myMap.set("a", true);
    for (let [k, v] of myMap) {
        console.log(k + "=" + v);
    }
    
    0 讨论(0)
  • 2020-12-07 16:54

    This worked for me.

    Object.keys(myMap).map( key => {
        console.log("key: " + key);
        console.log("value: " + myMap[key]);
    });
    
    0 讨论(0)
  • 2020-12-07 16:55

    Per the TypeScript 2.3 release notes on "New --downlevelIteration":

    for..of statements, Array Destructuring, and Spread elements in Array, Call, and New expressions support Symbol.iterator in ES5/E3 if available when using --downlevelIteration

    This is not enabled by default! Add "downlevelIteration": true to your tsconfig.json, or pass --downlevelIteration flag to tsc, to get full iterator support.

    With this in place, you can write for (let keyval of myMap) {...} and keyval's type will be automatically inferred.


    Why is this turned off by default? According to TypeScript contributor @aluanhaddad,

    It is optional because it has a very significant impact on the size of generated code, and potentially on performance, for all uses of iterables (including arrays).

    If you can target ES2015 ("target": "es2015" in tsconfig.json or tsc --target ES2015) or later, enabling downlevelIteration is a no-brainer, but if you're targeting ES5/ES3, you might benchmark to ensure iterator support doesn't impact performance (if it does, you might be better off with Array.from conversion or forEach or some other workaround).

    0 讨论(0)
  • 2020-12-07 16:58

    This worked for me. TypeScript Version: 2.8.3

    for (const [key, value] of Object.entries(myMap)) { 
        console.log(key, value);
    }
    
    0 讨论(0)
  • 2020-12-07 16:59

    Just use Array.from() method to convert it to an Array:

    myMap : Map<string, boolean>;
    for(let key of Array.from( myMap.keys()) ) {
       console.log(key);
    }
    
    0 讨论(0)
  • 2020-12-07 17:00

    es6

    for (let [key, value] of map) {
        console.log(key, value);
    }
    

    es5

    for (let entry of Array.from(map.entries())) {
        let key = entry[0];
        let value = entry[1];
    }
    
    0 讨论(0)
提交回复
热议问题