![](/img/trans.png)
[英]How to get parent object value by using child array key value using Angular.js/Javascript
[英]JavaScript: How to get parent object key by child object value?
你能幫我做一個能夠通過子對象值找到父對象鍵的函數嗎?
這是對象結構:
const mainObject = {
FIRST: {
key1: 'value1',
key2: 'value2',
},
SECOND: {
key3: 'value3',
key4: 'value4',
},
};
我嘗試使用此功能:
function getKeyByValue(object, value) {
return Object.keys(object).find((key) => object[key] === value);
}
但是如果我運行getKeyByValue(mainObject, 'value4')
它返回未定義。
有人可以幫助我如何改進 getKeyByValue 函數以獲取父鍵(我需要獲取“第二個”名稱)?
你的問題是你檢查了錯誤的鍵(對象)
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'));
遞歸執行是一種選擇
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.