javascriptecmascript-6array.prototype.map

How to use .map() over Map keys in Javascript


When using the Javascript built in Map, how do you use .map() to iterate over the keys?

I know the for...of can be used as shown below:

const map = new Map();

map.set(0, 'Zero');
map.set(1, 'One');
map.set(2, 'Two');

for (let key of map.keys()) {
  console.log(key);
}

But this code will fail:

map.keys().map(key => {
  console.log(key);
});

Solution

  • It's Array.prototype.map actually, it's defined for arrays, so use Array.from to convert the keys to an array and then use map:

    const map = new Map();
    
    map.set(0, 'Zero');
    map.set(1, 'One');
    map.set(2, 'Two');
    
    console.log(...Array.from(map.keys()).map(key => {
      return key ** 2; // square the keys
    }));