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:
function search(name){
if (friends[name]) alert(friends[name].firstName);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.