Searching for a friend.. If statements are not working


#1

var friends = {};
//adds objects inside friends object
var name = prompt("What name are you looking for?").toLowerCase;
friends.bill = {
firstName: "Bill",
lastName: "Last",
number: "313-224-1212",
address: ["The block rd","Detroit", "MI", "48223"]
};
friends.steve = {
firstName: "Steve",
lastName: "First",
number: "313-323-4545",
address: ["Down rd","Dearborn", "MI", "48020"]
};

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

for(var key in friends)
{
    if(friends[key].firstName === name)
    {
       console.log("contact info");
       return friends[key];
    }
    else
    {
        console.log("Sorry! Not a friend of mine.");
        break;
    }

}

};
//list();
search();

Can't seem to get the loop to increment through the friends object and compare "firstName === name". Also, are we comparing a property of an object (that property being "firstName") to a declared variable (that being "var name")? To me it seems the loop is not incrementing properly.


#2

Hi There. Pass a string name (like "Steve") to search

search("Steve")


#3

Yeah it only prints the "else" statement...seems to not compare the names to the string.


#4

How do I search through the properties of an object.


#5

Hi there,

So I made a few changes to the code. The main problem might have been that name.toLowerCase was not being called with (). I also changed the way the loop inside search exited. Instead of using else, we return from the loop if the person is matched. Once the loop is exhausted, the rest of search is executed. In our case, logging out the not found message.

var friends = {};

friends.bill = {
  firstName: 'Bill',
  lastName: 'Last',
  number: '313-224-1212',
  address: ['The block rd','Detroit', 'MI', '48223']
};

friends.steve = {
  firstName: 'Steve',
  lastName: 'First',
  number: '313-323-4545',
  address: ['Down rd','Dearborn', 'MI', '48020']
};

var search = function(name) {
  for (var key in friends) {
      if(friends[key].firstName === name) {
        console.log('contact info');
        return friends[key];
      }
  }
  console.log('Sorry! Not a friend of mine.');
};

var steve = search('Steve'); // "contact info"

#6

Or, we could use toLowerCase to match the key:

var search = function(name) {
  var lowerCased = name.toLowerCase();
  for (var key in friends) {
      if(key === lowerCased) {
        console.log('contact info');
        return friends[key];
      }
  }
  console.log('Sorry! Not a friend of mine.');
};