.map() a Javascript ES6 Map?

前端 未结 13 2143
不思量自难忘°
不思量自难忘° 2020-12-04 20:53

How would you do this? Instinctively, I want to do:

var myMap = new Map([[\"thing1\", 1], [\"thing2\", 2], [\"thing3\", 3]]);

// wishful, ignorant thinking
         


        
13条回答
  •  遥遥无期
    2020-12-04 21:23

    Using Array.from I wrote a Typescript function that maps the values:

    function mapKeys(m: Map, fn: (this: void, v: V) => U): Map {
      function transformPair([k, v]: [T, V]): [T, U] {
        return [k, fn(v)]
      }
      return new Map(Array.from(m.entries(), transformPair));
    }
    
    const m = new Map([[1, 2], [3, 4]]);
    console.log(mapKeys(m, i => i + 1));
    // Map { 1 => 3, 3 => 5 }
    

提交回复
热议问题