我有以下对象
{
"locations": {
"Base 1": {
"title": "This is base 1",
"Suburb 1": {
"title": "Suburb 1 in Base 1",
"Area A": {
"title": "Title for Area A",
"Street S1": {
"title": "Street S1 title"
},
"Street C4": {
"title": "Street C4 title"
},
"Street B7": {
"title": "Street B7 title"
}
},
"Another Area": {
"title": "Title for Area A",
"Street S1": {
"title": "Street S1 title"
},
"Street C4": {
"title": "Street C4 title"
},
"Street B7": {
"title": "Street B7 title"
}
}
},
"Another Suburb": {
"title": "Suburb 1 in Base 1",
"Area A": {
"title": "Title for Area A",
"Street S1": {
"title": "Street S1 title"
},
"Street C4": {
"title": "Street C4 title"
},
"Street B7": {
"title": "Street B7 title"
}
},
"Another Area": {
"title": "Title for Area A",
"Street S1": {
"title": "Street S1 title"
},
"Street C4": {
"title": "Street C4 title"
},
"Street B7": {
"title": "Street B7 title"
}
}
}
},
"Base2": {}
}
}
我得到了从“位置”对象中获取“标题”的数组,每个数组可以不同。我知道我可以像这样访问个人值:
locations["Base 1"]["title"]
locations["Base 1"]["Another Suburb"]["title"]
locations["Base 1"]["Another Suburb"]["Area A"]["title"]
etc etc.
但是如果我得到这样的数组,我不确定如何获取 title 的值:
AnArray = ["Base 1", "title"];
AnArray = ["Base 1", "Another Suburb", "title"];
AnArray = ["Base 1", "Another Suburb", "Area A", "title"];
AnArray = ["Base 1", "Another Suburb", "Another Area", "title"];
有没有办法解析/使用这些数组,以便每个数组都从位置对象返回正确的标题值?
我必须在每种情况下获取标题的值,我什至不确定从哪里开始。我尝试加入数组,然后获取“标题”值,但这似乎不起作用。
菜鸟,所以请不要介意这个问题听起来很愚蠢/或没有意义。
所以问题是,当引用在数组中时,如何从分层对象中获取值?
最佳答案
function getNested(obj, ar_keys) {
var innerObj = obj;
for(var i=0,il=ar_keys.length; i<il; i++){
innerObj = innerObj[ar_keys[i]];
}
return innerObj;
}
你可以这样调用它
getNested(x['locations'], ar_keys);
其中 x 是您的对象,ar_keys 是键数组。
关于javascript - 当引用在数组中时,如何从分层对象中获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15758764/