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!
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]);
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With