7/8 Search for a friend (Did you create a function called search?)


#1

Hello,

Here's is my code so far...

var friends = new Object();

    friends.bill= new Object();
    friends.bill.firstName = "Bill";
    friends.bill.lastName = "Gates";
    friends.bill.number = "206-555-5555";
    friends.bill.address = ['1111', 'Some Address', 'Seattle', 'WA', '66666'];
    friends.steve= new Object();
    friends.steve.firstName = "Steve";
    friends.steve.lastName = "Jobs";
    friends.steve.number ="415-666-6666";
    friends.steve.address = ['2222', 'Sweet Paradise', 'Cupertino', 'CA', '99999'];
var list = function (object) {
    for (var key in object) {
        console.log(key);
    }
};


var search = function(name) {
    for (var key in object) {
        if(friends[key].firstName === name) {
            console.log(friends[key]);
            return friends[key];
        }
        else {
            return 'none'
        }
    }
};
list (friends)
search ('Bill')

Any help would be appreciated!!


#2

A simple fix...

for (var key in object) {

should read,

for (var key in friends) {

#3

Thank you for responding! This didn't seem to work however... I got an error that read:
"It looks like your search function doesn't return contact information for Steve"

My code was (just so you can confirm I did what you suggested correctly!):

var friends = new Object();

    friends.bill= new Object();
    friends.bill.firstName = "Bill";
    friends.bill.lastName = "Gates";
    friends.bill.number = "206-555-5555";
    friends.bill.address = ['1111', 'Some Address', 'Seattle', 'WA', '66666'];
    friends.steve= new Object();
    friends.steve.firstName = "Steve";
    friends.steve.lastName = "Jobs";
    friends.steve.number ="415-666-6666";
    friends.steve.address = ['2222', 'Sweet Paradise', 'Cupertino', 'CA', '99999'];
var list = function (object) {
    for (var key in object) {
        console.log(key);
    }
};


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

When I run the code the result is:

bill
steve
{ firstName: 'Bill',
  lastName: 'Gates',
  number: '206-555-5555',
  address: [ '1111', 'Some Address', 'Seattle', 'WA', '66666' ] }
{ firstName: 'Bill',
  lastName: 'Gates',
  number: '206-555-5555',
  address: [ '1111', 'Some Address', 'Seattle', 'WA', '66666' ] }
{"firstName":"Bill","lastName":"Gates","number":"206-555-5555","address":["1111","Some Address","Seattle","WA","66666"]}

I am quite confused at this point...


#4

Remove this segment,

    else {
        return 'none'
    }

Since you have it written inside the loop, it returns 'none`. The loop should keep running, until it finds something.


#5

I see! Alright excellent -- thank you so much!