如何在Javascript映射中交换键和值 [英] How to swap Key and Value in Javascript map

查看:103
本文介绍了如何在Javascript映射中交换键和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这张ES6地图:

  Map(6){ Coratia => ; 1,韩国 => ;,挪威 => 2,慕尼黑 => 1,奥地利 => 1,...} 

我想交换键和值以使其像这样:

  Map(6){1 =>  Coratia,1 => 韩国,2 => 挪威,1 => 慕尼黑,1 => 澳大利亚,...} 


解决方案

一种使用 CodyKnapp 提到的想法的解决方案。它使用 Array.reduce()生成 value->密钥反向 Map



< pre class = snippet-code-js lang-js prettyprint-override> let myMap = new Map([[ Cortia,1],[ Korea,1],[挪威 ,2]]); //生成反向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()); //记录新生成的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;}  



注意 ,如评论中所述,您不能有一个地图可以将相同的 key 复制到多个


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:

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

解决方案

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.

这篇关于如何在Javascript映射中交换键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆