Nor*_*an 5 javascript arrays javascript-objects
我有以下对象
{
"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": {}
}
}
Run Code Online (Sandbox Code Playgroud)
我得到了数组来从“位置”对象中获取“标题”,并且每个数组可以不同。我知道我可以像这样访问个人价值观:
locations["Base 1"]["title"]
locations["Base 1"]["Another Suburb"]["title"]
locations["Base 1"]["Another Suburb"]["Area A"]["title"]
etc etc.
Run Code Online (Sandbox Code Playgroud)
但如果给我这样的数组,我不确定如何获取 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"];
Run Code Online (Sandbox Code Playgroud)
有没有办法解析/使用这些数组,以便每个数组从位置对象返回正确的标题值?
我必须在每种情况下获取标题的值,而且我什至不知道从哪里开始。我尝试加入数组,然后获取“标题”值,但这似乎不起作用。
这里是菜鸟,所以请不要介意这个问题是否听起来很愚蠢/或毫无意义。
所以问题是,当引用位于数组中时,如何从分层对象中获取值?
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;
}
Run Code Online (Sandbox Code Playgroud)
你会这样称呼它
getNested(x['locations'], ar_keys);
Run Code Online (Sandbox Code Playgroud)
其中 x 是您的对象,ar_keys 是键数组。