.map() a Javascript ES6 Map?

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

    Maybe this way:

    const m = new Map([["a", 1], ["b", 2], ["c", 3]]);
    m.map((k, v) => [k, v * 2]); // Map { 'a' => 2, 'b' => 4, 'c' => 6 }
    

    You would only need to monkey patch Map before:

    Map.prototype.map = function(func){
        return new Map(Array.from(this, ([k, v]) => func(k, v)));
    }
    

    We could have wrote a simpler form of this patch:

    Map.prototype.map = function(func){
        return new Map(Array.from(this, func));
    }
    

    But we would have forced us to then write m.map(([k, v]) => [k, v * 2]); which seems a bit more painful and ugly to me.

    Mapping values only

    We could also map values only, but I wouldn't advice going for that solution as it is too specific. Nevertheless it can be done and we would have the following API:

    const m = new Map([["a", 1], ["b", 2], ["c", 3]]);
    m.map(v => v * 2); // Map { 'a' => 2, 'b' => 4, 'c' => 6 }
    

    Just like before patching this way:

    Map.prototype.map = function(func){
        return new Map(Array.from(this, ([k, v]) => [k, func(v)]));
    }
    

    Maybe you can have both, naming the second mapValues to make it clear that you are not actually mapping the object as it would probably be expected.

提交回复
热议问题