Search code examples
javascriptecmascript-6javascript-objects

Create JavaScript object from swaped key and value ES6 Map


I have this ES6 map:

Map(6) {"Coratia" => 1, "Korea" =>, "Norway" => 2, "Munich" => 1, "Austrlia" => 1, ...}

I'd like to swap the key and values to make it like this:

 {1 => "Coratia", 1 => "Korea", 2 => "Norway", 1 => "Munich", 1 => "Australia", ...}

Solution

  • Here you have one solution that uses the idea mentioned by CodyKnapp. It uses Array.reduce() to generate the value->key reverse Map.

    let myMap = new Map([
       ["Cortia", 1],
       ["Korea", 1],
       ["Norway", 2]
    ]);
    
    // Generate the reverse Map.
    
    let res = [...myMap.entries()].reduce((acc, [k, v]) =>
    {
        acc.has(v) ? acc.set(v, acc.get(v).concat(k)) : acc.set(v, [k]);
        return acc;
    }, new Map());
    
    // Log the new generated Map.
    
    res.forEach((v, k) => console.log(`${k} => ${v}`));
    .as-console {background-color:black !important; color:lime;}
    .as-console-wrapper {max-height:100% !important; top:0;}

    Note, as mentioned in the commentaries, that you can't have a Map that will duplicate the same key for multiple different values.