通过其值获取 JavaScript 密钥- JavaScript
假设,我们有一个这样的对象 −
const products = {
"Pineapple":38,
"Apple":110,
"Pear":109
};密钥本身是唯一的,并且所有值本身是唯一的。我们需要编写一个接受值并返回其密钥的函数
例如:findKey(110) 应该返回 −
"Apple"
我们通过首先将值反向映射到密钥,然后简单地使用对象符号来查找它们的值来解决这一问题。
范例
以下是代码 −
const products = {
"Pineapple":38,
"Apple":110,
"Pear":109
};
const findKey = (obj, val) => {
const res = {};
Object.keys(obj).map(key => {
res[obj[key]] = key;
});
// if the value is not present in the object
// return false
return res[val] || false;
};
console.log(findKey(products, 110));输出
这将在控制台中产生以下输出 −
Apple
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP