Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
});
like image 991
Tony Scialo Avatar asked Mar 27 '26 05:03

Tony Scialo


2 Answers

Map.keys() returns an iterator you can spread the iterator using spread syntax

const map = new Map();

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

[...map.keys()].forEach(key => {
  console.log(key);
})
like image 51
Code Maniac Avatar answered Mar 28 '26 19:03

Code Maniac


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
}));
like image 36
MrGeek Avatar answered Mar 28 '26 17:03

MrGeek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!