Reputation: 817
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');
Upvotes: 3
Views: 5168
Reputation: 3765
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);
}
Upvotes: 6