简体   繁体   English

如何从 javascript 中的 Map object 获取特定密钥

[英]How to get a specific key from Map object in javascript

I have a map object and I would like to get the value of a specific key ( the value of key it self ) from the Map object let say we want to get 'correct' I have a map object and I would like to get the value of a specific key ( the value of key it self ) from the Map object let say we want to get 'correct'

we can get the values of 'correct' key by: question.get('correct') // return 3 but i want: someCode //return 'correct'我们可以通过以下方式获取“正确”键的值: question.get('correct') // return 3但我想要: someCode //return 'correct'

const question = new Map();

question.set('question','What is the latest version of javasript ?')
question.set(1,'es4')
question.set(2,'es5')
question.set(3,'es6')
question.set('correct',3)
question.set(true , 'correct Answer');
question.set(false , 'wrong Answer')

If your use case is just to test the existence of key then simply use has , but if you want to get key back if it present else some other value then you can use has to test key is present or not, here getKey function check if key is present on Map return that key else return Not found如果您的用例只是为了测试密钥的存在,那么只需使用has ,但是如果您想取回密钥,如果它存在其他值,那么您可以使用has测试密钥是否存在,这里getKey function 检查是否密钥存在于 Map 返回该密钥否则返回Not found

 const question = new Map(); question.set('question','What is the latest version of javasript?') question.set(1,'es4') question.set(2,'es5') question.set(3,'es6') question.set('correct',3) question.set(true, 'correct Answer'); question.set(false, 'wrong Answer') let getKey = key => question.has(key)? key: 'Not found' console.log(getKey('correct')) console.log(getKey('randome key'))

You can even use [...Map.keys()] to get array of keys and then iterator over and find if the value is found or not您甚至可以使用[...Map.keys()]来获取键数组,然后迭代并查找是否找到该值

To get a key based on a value, you can iterate over map entries using Map.entries() and return the key if found.要基于值获取键,您可以使用Map.entries()遍历 map 条目,如果找到则返回键。

 const question = new Map(); question.set('question','What is the latest version of javasript?'); question.set(1,'es4'); question.set(2,'es5'); question.set(3,'es6'); question.set('correct',3); question.set(true, 'correct Answer'); question.set(false, 'wrong Answer'); function getKey(map, input) { for (let [key, value] of map.entries()) { if (value === input) { return key; } } return "Not found"; } console.log(getKey(question, 3)); console.log(getKey(question, 2));

You can get the values of keys as follows which will get all the keys of the map object:您可以按如下方式获取键的值,这将获取 map object 的所有键:

question.keys();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM