Search for name


#1

I studied some moreposts on this topic and changed my search function. No my error msg asks me if I wrote a search function. The console prints out "No match found".
Does anyone understand my problem with logic? I don't know what I don't understand.....
Thanks.

var friends = {
    bill: {
        firstName: "Bill",
        lastName: "Gates",
        number: "(206) 555-5555",
        address: ['One Microsoft Way', 'Redmond', 'WA','98052']
    },
    steve: { 
        firstName: "Steve",
        lastName: "Jobs",
        number: "(206) 555-3333",
        address: ['34 Bay Drive', 'Seattle', 'WA','98052']
    },
    joanie: {
        firstName: "Joanie",
        lastName: "Cat",
        number: "(555) 555-1212",
        address: ['12 MainCat Ave','Las Vegas','NV','89222']
    }
};
var list = function(friends){
    for (var firstName in friends)
    { console.log(firstName);}
}
var search = function(name){
    for (var firstName in friends ){
        if(friends[firstName].firstName === name){
        console.log(firstName, lastName, number, address);
        return friends;
        }        else{ console.log("No match found");
        }
       }
    
};

#2

Hi :slightly_smiling:

So, this is what your code should look like:

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

Rather than:

var search = function(name){
    for (var firstName in friends ){ /* change firstName to key */
        if(friends[firstName].firstName === name){ /* should say: if (friends[key].firstName === name) { */
        console.log(firstName, lastName, number, address); /* this should log: friends[key] */
        return friends; /* should return friends[key]; */
        }        else{ console.log("No match found");
        }
       }
};

#3

Thanks. I made the changes and ran it. The console outputted a list of Steve's info.
But, I left the list function in my code, shouldn't it have printed out a list of the 3 first names?
This is the output:

{ firstName: 'Steve',
  lastName: 'Jobs',
  number: '(206) 555-3333',
  address: [ '34 Bay Drive', 'Seattle', 'WA', '98052' ] }
{"firstName":"Steve","lastName":"Jobs","number":"(206) 555-3333","address":["34 Bay Drive","Seattle","WA","98052"]}

#4

@mccbjnn,

+++ friends list and search and for-in explained.
Look here for an explanation
object
function
for-in-loop
list-function
search-function
http://www.codecademy.com/forum_questions/545275fd8c1ccc8e3e000a23#comment-5457b12c9c4e9d87cb00003f