typescriptes6-map

Learning to loop over a Map issue


I've been following along an online tutorial on ES6/Typescript and use of Map structures.

Location: https://codecraft.tv/courses/angular/es6-typescript/mapset/

Issue is that nothing displays from the loops at all. I have compared what I have written tot he tutorial and cannot for the life of me understand why it will not output the data in the for loops.

Would someone please tell me why this does not work when the code on the tutorial video shows that it does?

Here is the code

function mapDisplay(){
        let ddData = new Map([
          ["this", 11],
          ["doesnt", 21],
          ["work", 31]
        ])
    
        console.log('show ddData');
        console.log(ddData);
    
        console.log('show key');
        // Loop over our Map using keys function
        for (let key of ddData.keys()) {
          console.log(key);
        }
    
        console.log('show values')
        // Loop over our Map using values function
        for (let val of ddData.values()) {
          console.log(val);
        }

        console.log('show entries')
        // Loop over our Map using entries function
        for (let entry of ddData.entries()) {
          console.log(entry[0], entry[1]);
        }
      }
    
      mapDisplay();

What I see in the output console is this. As you can see no output comes from the loops:

enter image description here


Solution

  • Map.values()/Map.keys() returns an Iterator object [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/values. You should convert to Array using Array.from().

    See the following code -

    function mapDisplay(){
        let ddData = new Map([
          ["this", 11],
          ["doesnt", 21],
          ["work", 31]
        ]);
    
        console.log('show ddData');
        console.log(ddData);
    
        console.log('show key');
        // Loop over our Map using keys function
        for (let key of Array.from(ddData.keys())) {
          console.log(key);
        }
    
        console.log('show values')
        // Loop over our Map using values function
        for (let val of Array.from(ddData.values())) {
          console.log(val);
        }
    
        console.log('show entries')
        // Loop over our Map using entries function
        for (let entry of Array.from(ddData.entries())) {
          console.log(entry[0], entry[1]);
        }
      }
    
      mapDisplay();