Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 767
NSjonas Avatar asked Jan 03 '23 21:01

NSjonas


2 Answers

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]);
like image 161
trincot Avatar answered Jan 05 '23 09:01

trincot


You could transform it into array using spread syntax ..., apply map() method and then again transform it to Map

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

const negativeMap = new Map([...positiveMap].map(([k, v]) => [k, v * -1]))
console.log([...negativeMap])
like image 43
Nenad Vracar Avatar answered Jan 05 '23 10:01

Nenad Vracar