从交换的键和值ES6映射创建JavaScript对象

我有此ES6映射:

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

我想交换键和值,使其如下所示:

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

解决方案

这里您有一个使用CodyKnapp提到的想法的解决方案。它使用Array.reduce()生成value->key反转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;}

注意如注释中所述,您不能拥有将为多个不同的values复制相同的keyMap

相关文章