如何按其值获取JavaScript“地图"中的键? [英] How can I get a key in a JavaScript 'Map' by its value?
本文介绍了如何按其值获取JavaScript“地图"中的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的JavaScript地图"
I have a JavaScript 'Map' like this one
let people = new Map();
people.set('1', 'jhon');
people.set('2', 'jasmein');
people.set('3', 'abdo');
我想要一些方法,以按其值返回键.
I want some method to return a key by its value.
let jhonKey = people.getKey('jhon'); // jhonKey should be '1'
推荐答案
您可以将其转换为条目数组(使用 [... people.entries()]
)并进行搜索在那个数组中.
You could convert it to an array of entries (using [...people.entries()]
) and search for it within that array.
let people = new Map();
people.set('1', 'jhon');
people.set('2', 'jasmein');
people.set('3', 'abdo');
let jhonKeys = [...people.entries()]
.filter(({ 1: v }) => v === 'jhon')
.map(([k]) => k);
console.log(jhonKeys); // if empty, no key found otherwise all found keys.
这篇关于如何按其值获取JavaScript“地图"中的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文