Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
like image 687
brooklynsweb Avatar asked Dec 02 '25 21:12

brooklynsweb


1 Answers

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);
}
like image 157
Vedran Šego Avatar answered Dec 05 '25 09:12

Vedran Šego



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!