[英]Accessing a property of an object that is nested inside another object in Javascript
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');
It is either 要么是
friends.steve.firstName
or 要么
friends["steve"].firstName
You don't need the for-loop, though: 但是,您不需要for循环:
function search(name){
if (friends[name]) alert(friends[name].firstName);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.