Search for a friend function issues


#1


https://www.codecademy.com/en/courses/javascript-beginner-en-3bmfN/0/7?curriculum_id=506324b3a7dffd00020bf661


search function is not working/not returning or sending info to console. I understand the answer that is displayed by with the page but I do not understand why this syntax doesn't work. IIterating through objects in an object (friend in friends) would mean that friend itself is one of the friend objects (steve or bill , etc). What am I missing?


var friends = {};

friends.bill = {
    firstName: "Bill",
    lastName: "Gates",
    number: "555-555-5555",
    address:["One Microsoft Way", "Redmond", "WA", "98052"],
};

friends.steve = {
    firstName: "Steve",
    lastName: "Jobs",
    number: "111-111-1111",
    address: ["One Apple Way", "Somewhere", "CA", "12345"],
};    

var list = function(obj) {
    for(var friend in friends)
    {
        console.log(friend);    
    }    
    
};    

var search = function(name) {
    for(var friend in friends)
    {
        if(name === friend.firstName)
        {
            console.log(friend);
            return friend;
        }
    }    
};


#2

what does friend contain? lets see:

var search = function(name) {
    for(var friend in friends)
    {
        console.log(friend);
    }
}

so, friend contains the properties in friend (bill and steve), so far so good, but now lets see if we can access the first name:

var search = function(name) {
    for(var friend in friends)
    {
        console.log(friend.firstName);
    }
}

auch, undefined. What went wrong? bill and steve are part of the friends object, so you need to tell your program that you want the first name of bill and steve stored in the the friends object:

friends[friend].firstName

#3

Isn't the for loop doing exactly that thought? Iterating one by one through the friend in friends?


#4

yes, the loop is doing this. But you can't access bill and steve directly, since they are of the friends object. so you need friends[friend].firstName

so you need to access the outer object first


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.