7. Search for friend


#1


It print "Friend not found" and steve's information the same time.
Error message: Oops, try again. Did you create a function called search?


var friends = {};
var friends = new Object();
friends.bill = new Object();
friends.bill.firstName = "bill";
friends.bill.lastName = "asd";
friends.bill.number = "123";
friends.bill.address = ["qwe", "rtty"];
friends.steve = new Object();
friends.steve.firstName = "steve";
friends.steve.lastName = "fgh";
friends.steve.number = "456";
friends.steve.address = ["klo", "iyu"];

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

var search = function(name){
    for(var prop in friends){
    if(friends[name].firstName == prop)
    {console.log("First Name: " + friends[prop].firstName);
    console.log("Last Name: " + friends[prop].lastName);
    console.log("number: " + friends[prop].number);
    console.log("address: " + friends[prop].address);
    return friends[name].firstName;}
    else
    {console.log("Friend not found");}
    }};
    
search("steve")


#2

var friends = {};
var friends = new Object();

You declared object twice. Please, remove one.

if(friends[name].firstName == prop)

You need compare name with firstName of every property in friends object:

if(friends[prop].firstName == name)

So, it prints "Friend not found" because the 1st property is bill and

// friends["bill"].firstName is "bill"
if(friends["bill"].firstName == "steve") { // returns false
...
} else {
console.log("Friend not found");
}

That's why you have "Friend not found" and steve's information.


#3

Thank you so much.
It's very helpful.


#4

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