Search code examples
javascripttypescriptes6-map

ES6 Map: transform values


I'm working on a project where I frequently have to transform every value in an ES6 map:

const positiveMap = new Map(
  [
    ['hello', 1],
    ['world', 2]
  ]
);

const negativeMap = new Map<string, number>();
for (const key of positiveMap.keys()) {
  negativeMap.set(key, positiveMap.get(key) * -1);
}

Just wondering if there is maybe a better way of doing this? Ideally a one liner like Array.map().

Bonus points (not really), if it compiles in typescript!


Solution

  • You could use the Array.from 2nd argument, a map-style callback:

    const positiveMap = new Map([['hello', 1],['world', 2]]),
        negativeMap = new Map(Array.from(positiveMap, ([k, v]) => [k, -v]));
    
    console.log([...negativeMap]);