.map() a Javascript ES6 Map?

前端 未结 13 2137
不思量自难忘°
不思量自难忘° 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:28

    Actually you can still have a Map with the original keys after converting to array with Array.from. That's possible by returning an array, where the first item is the key, and the second is the transformed value.

    const originalMap = new Map([
      ["thing1", 1], ["thing2", 2], ["thing3", 3]
    ]);
    
    const arrayMap = Array.from(originalMap, ([key, value]) => {
        return [key, value + 1]; // return an array
    });
    
    const alteredMap = new Map(arrayMap);
    
    console.log(originalMap); // Map { 'thing1' => 1, 'thing2' => 2, 'thing3' => 3 }
    console.log(alteredMap);  // Map { 'thing1' => 2, 'thing2' => 3, 'thing3' => 4 }
    

    If you don't return that key as the first array item, you loose your Map keys.

    0 讨论(0)
提交回复
热议问题