Search code examples
javascriptdictionaryecmascript-6

Using a map function on a 'Map' to change values


I can use a Map and then set values:

const a = new Map([["a", "b"], ["c", "d"]])

Now if I want to apply a function to all values in a functional way (without for ... of or .forEach), I thought I could have done something like this:

const b = a.map(([k, v]) => [k, doSomethingWith(v)]);

But there is no map function on a Map. Is there a built-in/elegant way to map a Map?


Solution

  • You could use Array.from for getting entries and mapping new values and take this result for a new Map.

    const b = new Map(Array.from(
        a, 
        ([k, v]) => [k, doSomethingWith(v)]
    ));