如何通过值获取 JavaScript Map 中的键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47135661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a key in a JavaScript Map by its value?
提问by Engineer Passion
I have a js Map like this one
我有一个像这样的 js 地图
let people = new Map();
people.set('1', 'jhon');
people.set('2', 'jasmein');
people.set('3', 'abdo');
what I want is some method to return a key by its value
我想要的是某种通过键值返回键的方法
let jhonKey = people.getKey('jhon'); // jhonKey should be '1'
回答by Nina Scholz
You could seach for it in an array of entries.
您可以在条目数组中搜索它。
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 foudn otherwise all found keys.
回答by Rajesh
You can use for..ofloop to loop directly over the map.entries and get the keys.
您可以使用for..of循环直接遍历 map.entries 并获取密钥。
function getByValue(map, searchValue) {
for (let [key, value] of map.entries()) {
if (value === searchValue)
return key;
}
}
let people = new Map();
people.set('1', 'jhon');
people.set('2', 'jasmein');
people.set('3', 'abdo');
console.log(getByValue(people, 'jhon'))
console.log(getByValue(people, 'abdo'))
回答by David Spillett
There is no direct method for picking out information in this direction, so if all you have is the map you need to loop through the set as suggested by others.
在这个方向上没有直接的方法来挑选信息,所以如果你只有地图,你需要按照其他人的建议循环遍历该集合。
If the map/array/other is large enough that such a loop would be a performance issue and the requirement for a reverse lookup is common within the project, you could implement your own structure using a pair of maps/arrays/other with one as per the current object and the other with the key and value reversed. That way the reverse lookup is as efficient as the normal one. Of course, you have more work to do as you need to implement each method that you need as a pass-through to one or both of the underlying objects so if the map is small and/or the reverse lookup is not needed often the scan-via-loop option is likely to be preferable due to being simpler to maintain and possible simpler for the JiT compiler to optimise.
如果 map/array/other 足够大以至于这样的循环会是一个性能问题,并且项目中需要反向查找是常见的,你可以使用一对 map/arrays/other 来实现你自己的结构,其中一个作为每个当前对象和另一个键和值相反。这样反向查找与正常查找一样有效。当然,您有更多的工作要做,因为您需要实现您需要的每个方法作为传递到一个或两个基础对象的方法,因此如果地图很小和/或通常不需要反向查找,则扫描-via-loop 选项可能更可取,因为它更易于维护并且可能更易于 JiT 编译器优化。
In any case one thing to be wary of is the possibility that multiple keys could have the same value. If this is possible then when looping the through your map you need to decide if you are fine to return one of the possible keys arbitrarily (probably the first one) or if you want to return an array of keys, and if implementing a reverse index for data that could have duplicate values the same issue also needs to be accounted for.
在任何情况下,需要注意的一件事是多个键可能具有相同的值。如果这是可能的,那么在循环遍历您的地图时,您需要决定是否可以任意返回一个可能的键(可能是第一个),或者是否要返回一个键数组,以及是否实现反向索引对于可能具有重复值的数据,同样的问题也需要考虑在内。
回答by Nitish Narang
Though late and other great answers already exist, still you can give below "..." and "Array.find" a try
尽管已经存在迟到和其他很棒的答案,但您仍然可以尝试在下面的“...”和“Array.find”
let people = new Map();
people.set('1', 'jhon');
people.set('2', 'jasmein');
people.set('3', 'abdo');
function getKey(value) {
return [...people].find(([key, val]) => val == value)[0]
}
console.log('Jasmein - ',getKey('jasmein'))
console.log('Jhon - ',getKey('jhon'))
回答by Lior Elrom
JavaScript Mapand Object
JavaScript地图和对象
Given a JavaScript Map, I like @Nitish answer:
给定一个 JavaScript Map,我喜欢 @Nitish 的回答:
const map = new Map([
[1, 'one'],
[2, 'two'],
[3, 'three'],
]);
function getKey(val) {
return [...map].find(([key, value]) => val === value)[0];
}
console.log(getKey('one')); // 1
console.log(getKey('two')); // 2
console.log(getKey('three')); // 3
For a JavaScript object, you could do something like so:
对于 JavaScript 对象,您可以执行以下操作:
const map = {
1: 'one',
2: 'two',
3: 'three',
};
function getKey(val) {
return Object.keys(map).find(key => map[key] === val);
}
console.log(getKey('one')); // 1
console.log(getKey('two')); // 2
console.log(getKey('three')); // 3
回答by IliasT
One could invert the Map so that the keys are the values and the values are the keys and then lookup the original value as a key. Here's an example:
可以反转 Map 以便键是值,值是键,然后查找原始值作为键。下面是一个例子:
let myMap = new Map([
[1, 'one'],
[2, 'two'],
[3, 'three'],
]);
let invertedMap = new Map([...myMap.entries()].map(
([key, value]) => ([value, key]))
);
console.log(invertedMap.get('one'))
// => 1
回答by John
my typescript version
我的打字稿版本
const getByValue = <A, B>(m: Map<A,B>, searchValue: B):[A, B] | undefined => {
const l:IterableIterator<[A, B]> = m.entries();
const a:[A, B][] = Array.from(l);
return a.find(([_k,v]) => v === searchValue);
}

