我该如何按值获取密钥?
这是我的代码。
function getkey(obj, key) {
for (i = 0; i < obj.length; i++) {
if (obj[i] === key) {
return obj[i];
}
}
}
var json = {
test: {
"key1": {
"inkey1": "value1",
"inkey2": "value2"
},
"key2": {
"inkey3": "value3",
"inkey4": "value4"
}
}
}
console.log(getkey(json, "value2"));
我想按值2获取key1 我如何获得key1?
请帮助我!
答案 0 :(得分:1)
有许多方法可以做到这一点,一种方法是对函数使用变体并应用递归。请参见下面的代码段:
function getkey(obj, key) {
for (i = 0; i < Object.keys(obj).length; i++) {
if (Object.values(obj)[i] === key) {
return Object.keys(obj)[i];
}
if (Object.values(obj)[i].constructor == Object) {
return getkey(Object.values(obj)[i], key)
}
}
}
var json = {
test: {
"key1": {
"inkey1": "value1",
"inkey2": "value2"
},
"key2": {
"inkey3": "value3",
"inkey4": "value4"
}
}
}
console.log(getkey(json, "value2"));
结果为inkey2
。无论键在对象中嵌套的深度如何,此方法都应起作用。
答案 1 :(得分:0)
对于非嵌套版本
function getKeyByValue(obj, value) {
for (let key in obj) {
for (let inkey in obj[key]) {
if (obj[key][inkey] === value) {
return key;
}
}
}
}
console.log(getKeyByValue(json['test'], "value2")); //key1
对于您不知道对象有多深的嵌套版本
function getKeyByValue(obj, value, path) {
path = path ? path + '.' : '';
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
if (obj[key] === value) {
return path + key;
} else if (typeof obj[key] === 'object') {
let found = getKeyByValue(obj[key], value, path + key);
if (found) {
return found;
}
}
}
}
}
console.log(getKeyByValue(json, "value2")); //"test.key1.inkey2"