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

6

10

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);
});
Rigidify answered 24/8, 2019 at 23:5 Comment(0)
C
5

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
}));
Carrelli answered 24/8, 2019 at 23:8 Comment(0)
O
6

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);
})
Orthographize answered 25/8, 2019 at 3:18 Comment(2)
There's no need to spread when using for..of because it conforms to the iterator protocol already.Bloodstock
@Bloodstock oops my bad !!, i meant to spread and then use any of the array method, updated, thanks for pointing outOrthographize
C
5

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
}));
Carrelli answered 24/8, 2019 at 23:8 Comment(0)
F
3

You can use Array.from():

const map = new Map();

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

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

Hopefully that helps!

Famous answered 24/8, 2019 at 23:8 Comment(0)
B
2

You might be better off using Array.from mapping function directly to avoid creating a temporary array:

Array.from(map.keys(), k => console.log(k))

Another, more verbose, but helpful option would be to redefine array iteration methods on the iterator prototype, thus making them automatically available for all iterators:

// http://www.ecma-international.org/ecma-262/7.0/#sec-%iteratorprototype%-object
const IteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()));

Object.defineProperties(IteratorPrototype, {
    forEach: {
        value: function (fn) {
            let n = 0;

            for (let x of this) {
                fn(x, n++, this);
            }
        },
        enumerable: false
    },
    
    map: {
        value: function (fn) {
            let n = 0, a = [];

            for (let x of this) {
                a.push(fn(x, n++, this));
            }

            return a;
        },
        enumerable: false
    },
    
    reduce: {
        value: function (fn, init) {
            let n = 0;

            if (arguments.length === 1) {
                init = this.next().value;
            }

            for (let x of this) {
                init = fn(init, x, n++, this);
            }

            return init;
        },
        enumerable: false
    },

});


/////

const map = new Map();

map.set('a', 'Zero');
map.set('b', 'One');
map.set('c', 'Two');

map.keys().map(console.log)

console.log(map.values().reduce((o, k) => o + '/' + k));

function* it() {
    yield 'x';
    yield 'y';
    yield 'z';
}

it().map(x => console.log(x))
Bloodstock answered 24/8, 2019 at 23:37 Comment(0)
T
1
map.forEach((_,key) => console.log(key));
Talkative answered 8/6, 2020 at 5:19 Comment(0)
A
0

const map = new Map([[0, "Zero"], [1, "One"], [2, "Two"]]);
    
const arr = Array.from(map, (entry) => ({ key: entry[0], value: entry[1] })); 

console.log(arr); 
         
Automation answered 13/1, 2023 at 10:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.