admin管理员组文章数量:1405136
I'm trying to access a property of an object that is nested inside an object. Am I approaching it the wrong way, is my syntax wrong, or both? I had more 'contacts objects inside, but eliminated them to shrink this post.
var friends = {
steve:{
firstName: "Rob",
lastName: "Petterson",
number: "100",
address: ['Thor Drive','Mere','NY','11230']
}
};
//test notation this works:
//alert(friends.steve.firstName);
function search(name){
for (var x in friends){
if(x === name){
/*alert the firstName of the Person Object inside the friends object
I thought this alert(friends.x.firstName);
how do I access an object inside of an object?*/
}
}
}
search('steve');
I'm trying to access a property of an object that is nested inside an object. Am I approaching it the wrong way, is my syntax wrong, or both? I had more 'contacts objects inside, but eliminated them to shrink this post.
var friends = {
steve:{
firstName: "Rob",
lastName: "Petterson",
number: "100",
address: ['Thor Drive','Mere','NY','11230']
}
};
//test notation this works:
//alert(friends.steve.firstName);
function search(name){
for (var x in friends){
if(x === name){
/*alert the firstName of the Person Object inside the friends object
I thought this alert(friends.x.firstName);
how do I access an object inside of an object?*/
}
}
}
search('steve');
Share
Improve this question
edited Oct 1, 2013 at 0:16
brooklynsweb
asked Oct 1, 2013 at 0:04
brooklynswebbrooklynsweb
8173 gold badges12 silver badges30 bronze badges
3
-
As
x
is a variable, you need to dofriends[x].firstName
.friends.x.firstname
would look for the literal keyx
. – Evan Davis Commented Oct 1, 2013 at 0:10 - That makes perfect sense, thanks! – brooklynsweb Commented Oct 1, 2013 at 0:19
- possible duplicate of Access / process (nested) objects, arrays or JSON – Felix Kling Commented Oct 1, 2013 at 1:26
1 Answer
Reset to default 6It is either
friends.steve.firstName
or
friends["steve"].firstName
You don't need the for-loop, though:
function search(name){
if (friends[name]) alert(friends[name].firstName);
}
版权声明:本文标题:json - Accessing a property of an object that is nested inside another object in Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744891574a2630812.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论