Iterating over Typescript Map

前端 未结 12 1696
无人共我
无人共我 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:35

    Using Array.from, Array.prototype.forEach(), and arrow functions:

    Iterate over the keys:

    Array.from(myMap.keys()).forEach(key => console.log(key));
    

    Iterate over the values:

    Array.from(myMap.values()).forEach(value => console.log(value));
    

    Iterate over the entries:

    Array.from(myMap.entries()).forEach(entry => console.log('Key: ' + entry[0] + ' Value: ' + entry[1]));
    
    0 讨论(0)
  • 2020-12-07 16:38

    Just a simple explanation to use it in an HTML document.

    If you have a Map of types (key, array) then you initialise the array this way:

    public cityShop: Map<string, Shop[]> = new Map();
    

    And to iterate over it, you create an array from key values.

    Just use it as an array as in:

    keys = Array.from(this.cityShop.keys());
    

    Then, in HTML, you can use:

    *ngFor="let key of keys"
    

    Inside this loop, you just get the array value with:

    this.cityShop.get(key)
    

    Done!

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

    If you don't really like nested functions, you can also iterate over the keys:

    myMap : Map<string, boolean>;
    for(let key of myMap) {
       if (myMap.hasOwnProperty(key)) {
           console.log(JSON.stringify({key: key, value: myMap[key]}));
       }
    }
    

    Note, you have to filter out the non-key iterations with the hasOwnProperty, if you don't do this, you get a warning or an error.

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

    On Typescript 3.5 and Angular 8 LTS, it was required to cast the type as follows:

    for (let [k, v] of Object.entries(someMap)) {
        console.log(k, v)
    }
    
    0 讨论(0)
  • 2020-12-07 16:46

    You could use Map.prototype.forEach((value, key, map) => void, thisArg?) : void instead

    Use it like this:

    myMap.forEach((value: boolean, key: string) => {
        console.log(key, value);
    });
    
    0 讨论(0)
  • 2020-12-07 16:48

    You can also apply the array map method to the Map.entries() iterable:

    [...myMap.entries()].map(
         ([key, value]: [string, number]) => console.log(key, value)
    );
    

    Also, as noted in other answers, you may have to enable down level iteration in your tsconfig.json (under compiler options):

      "downlevelIteration": true,
    
    0 讨论(0)
提交回复
热议问题