Hey i need help D:


#1

var friend = {
bill: {
firstName: "Bill",
lastName: "Gates",
number: "555-555-5555",
address: ['One Microsoft Way','Redmond','WA','98052']
}
};
var friend2 = {
steve: {
firstName: "Steve",
lastName: "Jobs",
number: "525-555-5555",
address: ['1 Infinite Loop','Cupertino','CA','99999']
}
};
var list = function (friend){
for (var key in friend) {
console.log(key);
}
}
var search = function(name) {
for (var key in friend) {
if (friend[key].firstName === name) {
console.log(friend[key]);
return friend[key];
}
else {
console.log(friend2[key]);
return friend2[key];
}
}
};
what did I do wrong?


#2

Your friend and friend2 objects should be combined into a single friends object which contains both bill and steve.


#3

Hi @luisornelas

I tried to correct your code, you can look and test it :

var search = function(object, name) {
    for (var key in object) {
    
    if(object[key].firstName === name){
        console.log(object[key]);
        return true;
    }else{
        console.log("I don't find it");
        return false;
    };
    };
};
search(friend,"Bill");

Hold on :wink:


#4

We need one object to house the friends (note the variable name):

var friends = {
    bill: {},
    steve: {}
};

The list function is close, but let's consider how to make it generic and re-usable:

var list = function (object) {
    for (var key in object) {
        console.log(key);
    }
};

list(friends);
/*
bill
steve
*/

Now the search() function. Before we begin, examine your code and the else statement inside the for statement. Consider, what will happen if the first iteration of the loop does not come up with a match to name? It will arbitrarily return (exit the function) which ends the loop before any possible match can be found.

var search = function (name) {
    for (var key in friends) {
        if (friends[key].firstName === name) {
            console.log(friends[key]);
            return friends[key];
    }
    return name + " was not found.";
};
search("Bill");

Notice where we return 'not found' ? Outside of and after the loop is completed.