[英]JavaScript: How to get parent object key by child object value?
can you help me to make a function that will be able to find parent object key by child object value?你能帮我做一个能够通过子对象值找到父对象键的函数吗?
This is object structure:这是对象结构:
const mainObject = {
FIRST: {
key1: 'value1',
key2: 'value2',
},
SECOND: {
key3: 'value3',
key4: 'value4',
},
};
I tried to use this function:我尝试使用此功能:
function getKeyByValue(object, value) {
return Object.keys(object).find((key) => object[key] === value);
}
but if I run getKeyByValue(mainObject, 'value4')
it returns undefined.但是如果我运行getKeyByValue(mainObject, 'value4')
它返回未定义。
Can someone help how I can improve getKeyByValue function to get the parent key (I need to get 'SECOND' name)?有人可以帮助我如何改进 getKeyByValue 函数以获取父键(我需要获取“第二个”名称)?
your problem is that you check the wrong keys (objects)你的问题是你检查了错误的键(对象)
const mainObject = { FIRST: { key1: 'value1', key2: 'value2', }, SECOND: { key3: 'value3', key4: 'value4', }, }; function getKeyByValue(object, value) { //you can see that the first keys are for the first objects (first and second) this method doesnt give nested keys. console.log(Object.keys(object)); return Object.keys(object).find((key) => Object.keys(object[key]).some((key2) => object[key][key2] === value)); } //you can also do this and check directly the values function getKeyByValue2(object, value) { //you can see that the first keys are for the first objects (first and second) this method doesnt give nested keys. console.log(Object.keys(object)); return Object.keys(object).find((key) => Object.values(object[key]).indexOf(value) > -1); } console.log(getKeyByValue(mainObject, 'value4')); console.log(getKeyByValue2(mainObject, 'value4'));
Doing it recursively is an option递归执行是一种选择
let path = []; let parent = ''; function getParent(path, json, value) { for (var key in json) { if (typeof json[key] === 'object') { path.push(key.toString()); getParent(path, json[key], value); path.pop(); } else { if (json[key] == value) { parent = path[0]; } } } } const mainObject = { FIRST: { key1: 'value1', key2: 'value2', }, SECOND: { key3: 'value3', key4: 'value4', }, }; getParent(path, mainObject, 'value4'); console.log(parent);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.