javascript – 当引用在数组中时,如何从分层对象中获取值?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 当引用在数组中时,如何从分层对象中获取值?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1859字,纯文字阅读大概需要3分钟。
内容图文
我有以下对象
{
"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"];
有没有办法解析/使用这些数组,所以每个都从位置对象返回正确的标题值?
我必须在每种情况下获取标题的值,我甚至不确定从哪里开始.我尝试加入数组然后获取’title’值,但这似乎不起作用.
Noob在这里,所以请不要介意这个问题听起来很愚蠢/或者没有意义.
所以问题是,当引用在数组中时,如何从分层对象中获取值?
解决方法:
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 – 当引用在数组中时,如何从分层对象中获取值?全部内容,希望文章能够帮你解决javascript – 当引用在数组中时,如何从分层对象中获取值?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。