从深层嵌套对象内的值获取父键和祖父母键 [英] Get parent and grandparent keys from a value inside a deep nested object
问题描述
我有一个深层嵌套的JavaScript对象,并且知道一个值位于该对象的最低位置.我想知道父密钥和祖父母密钥.
I’ve got a deep nested JavaScript Object and I know a value which is at the object’s lowest position. I want to know the parent key and grandparent key.
我设置了一个jsbin https://jsbin.com/yimugezuxe/edit?js,console
I set up a jsbin https://jsbin.com/yimugezuxe/edit?js,console
基于值"uniqueID#9aserdf",我想知道/返回其父键:下一个对象的阶段2"和级别2":
Based on the value 'uniqueID#9aserdf' I want to know/return its parent keys: 'Stage 2' and 'Level 2' from the object below:
const obj = {
"Level 1": {
"Stage 1": [
{
"title": "Parent 1",
"id": "Parent1#id",
"Children": [
{
"title": "Steve",
"id": "uniqueID1"
},
{
"title": "James",
"id": "uniqueID#9"
}
]
}
]
},
"Level 2": {
"Stage 1": [
{
"title": "Parent 4",
"id": "Parent4#id",
"Children": [
{
"title": "Tim",
"id": "uniqueIDadsf"
},
{
"title": "Hans",
"id": "uniqueID#9asdf"
}
]
}
],
"Stage 2": [
{
"title": "Parent 10",
"id": "Parent10#id",
"Children": [
{
"title": "Chris",
"id": "uniqueIDadsf33"
},
{
"title": "Jack",
"id": "uniqueID#9aserdf"
}
]
}
]
}
};
// based on the value 'uniqueID#9aserdf' I want to know/return its parent keys: 'Stage 2' and 'Level 2'
推荐答案
类似以下内容:
for (var prop in obj) {
for (var prop2 in obj[prop]) {
}
}
然后使用此方法向下迭代并检查
Then use this method to iterate down and check
这是一个完整的例子:
for (var prop in obj) {
for (var prop2 in obj[prop]) {
//console.log(prop2);
for (var prop3 in obj[prop][prop2]) {
//console.log("->"+prop3);
for (var prop4 in obj[prop][prop2][prop3]) {
//console.log("->"+"->"+prop4);
for (var prop5 in obj[prop][prop2][prop3][prop4]) {
//console.log("->"+"->"+"->"+prop5);
for (var prop6 in obj[prop][prop2][prop3][prop4][prop5]) {
//console.log("->"+"->"+"->"+"->"+prop6);
if (obj[prop][prop2][prop3][prop4][prop5][prop6] == "uniqueID#9aserdf") {
console.log("Stage :" +prop2 + " == Level :" + prop);
}
}
}
}
}
}
}
您可以删除代码中的注释,以帮助查看您在对象中的位置.
you can take away the comments in the code, to help see where you are in the object.
这篇关于从深层嵌套对象内的值获取父键和祖父母键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!