Why isn't this code acceptable?


#1

Could someone help me wrap my head around why this isn't correct?
Thanks!

var search= function(name){
if(name === friends.firstName || friends.lastName){
console.log( name);
}
}


#2

Hi @laurenb2015 , what's the rest of your code ?


#3

Oh sorry. Ok, so it's supposed to be searching through the object Friends to see if your search query matches anything in your address book. So:

var friends= {
bill:{
firstName: "Bill",
lastName: "Gates",
number: "555-555-5555",
address:["1513", "Markham Drive","Litte Rock","AR", "72201"]
},
steve:{
firstName: "Steve",
lastName: "Martin",
number: "666-666-6666",
address: ["2420", "Snickers Ave", "Little Rock","AR", "72201"]
}
};

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


#4

Instructions
Define a function search that takes a single argument, name. If the argument passed to the function matches any of the first names in friends, it should log that friend's contact information to the console and return it.


#5

Hi @laurenb2015

Your code

if(name === friends.firstName || friends.lastName){

is missing the object key that goes between "friends" and "firstName" or "lastName", ie. "bill" or "steve." so it should be either friends.bill.firstName or else the variable in place of "bill" that you are using.


#6

So @laurenb2015, try this:

var friends = {
bill:{
firstName: "Bill",
lastName: "Gates",
number: "555-555-5555",
address:["1513", "Markham Drive","Litte Rock","AR", "72201"]
},
steve:{
firstName: "Steve",
lastName: "Martin",
number: "666-666-6666",
address: ["2420", "Snickers Ave", "Little Rock","AR", "72201"]
}
};

var list = function(){
    for(var key in friends){
        console.log(key);
    };
};
var search = function(name){
    for(var key in friends){
        if(friends[key].firstName === name){
             console.log(friends[key]);
        };
    };
};

search(/*what you want*/);

Hold on :wink:


#7

Ah ok, because there are objects within objects?


#8

Yup! And when you reference specific object properties, you can't skip a level, otherwise the interpreter will look for a property that isn't there.


#9

Ah ok, so that seems very cumbersome in a search feature, like you already have to know what data is inside before creating your search function. I guess I assumed that if one object was holding multiple objects inside of it that somehow the search function could look inside without spelling out everything in there. But that is not the case.


#10

It seems that way, at least. I'm still learning this stuff so I don't know everything you can do... maybe you can use a wildcard or placeholder so that you don't have to spell out every single property key.