英文:
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([
['a', '1'],
['b', '2']
]);
// automatically make the second, inverted map
const dict2 = new Map([...dict1.entries()].map(([k, v]) => [v, k]));
console.log(dict2.get('1'));
<!-- 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论