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 do friends[x].firstName. friends.x.firstname would look for the literal key x. – 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
Add a ment  | 

1 Answer 1

Reset to default 6

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);
}

本文标签: jsonAccessing a property of an object that is nested inside another object in JavascriptStack Overflow