获取映射对象中的值的键

huangapple go评论67阅读模式
英文:

Get an value's key inside a map object

问题

const dict = new Map([
   ['a', '1'],
   ['b', '2']
]);

我们知道`dict.get(key)`返回值但如果我想要获取值对应的键呢

这个问题从未被提出我在Stack Overflow上搜索了3个小时他们都创建集合或其他东西这不是我所需的
英文:
const dict = new Map([
   ['a', '1'],
   ['b', '2']
]

We know that dict.get(key) returns the value but what if I want to get the key of value?

This question was never asked. I searched for 3 hours on stack overflow they all create sets or something I don't need

答案1

得分: 1

一般情况下,如果您需要访问双向数据,您可以使用两个映射(Map),如果键可能与值相同,则使用两个映射,否则只使用一个映射。

当您向其中一个映射添加内容时,请确保将其添加到另一个映射中,同时交换键和值。

如果您愿意,您还可以创建自己的类,使用映射(Map)作为底层数据结构,以使界面更易于使用。

英文:

Generally if you have two-way data that you need to access, you either have two maps if a key could be the same as a value, otherwise just a single map.

When you add something to one of these maps, make sure to add it to the other, with the keys/values swapped.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const dict1 = new Map([
   [&#39;a&#39;, &#39;1&#39;],
   [&#39;b&#39;, &#39;2&#39;]
]);

// automatically make the second, inverted map
const dict2 = new Map([...dict1.entries()].map(([k, v]) =&gt; [v, k]));

console.log(dict2.get(&#39;1&#39;));

<!-- end snippet -->

If you wanted to, you could also make your own class that uses Maps under the hood to make the interface easier to work with.

huangapple
  • 本文由 发表于 2023年2月6日 14:55:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75358189.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定