7/8 Search for A Friend


#1

What does friends[key].firstName mean? Why is there a '.' ? I don't understand the syntax.

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

I did the below instead and it still passed me.

var search = function(name){
if (name === "Bill"){
console.log(friends.bill);
return friends.bill;
}

if (name === "Steve"){
console.log(friends.steve);
return friends.steve;
}
};

search("Bill");


#2

You know when you're dealing with an array?

var search[0] = "Example"

Well it's basically the same thing,

The console sees this: "For every 'key' in the object, I'm going to do this code." And it works in the same way an array would work, running through the values of the Object and verifying that the 'firstname' for the object matches the name you're searching.


#3

thanks @lolman for your response! I think the confusing part is the object within the object in this exercise. Can you let me know if my thinking is correct?

var search = function(name) { <--- we have a search function with one parameter

for(var key in friends) { <--- for all the 'key' value that is in the 'friends' and 'friends.bill' and 'friends.steve' (not sure about this part)

if(friends[key].firstName === name) { <---- If either object 'friends.bill' or 'friends.steve' has a first name is equal to the parameter

(Also, another question I had: Is friends[key].firstName written out like this to mimic how friends.bill looks like when searching for the first name?)

console.log(friends.bill);
return friends.bill;
}

Ah, sorry for long response, just want to make sure I understand what is going on. These exercises are hard for me.

Thanks again.


#4

Well it's a little hard to explain that but it works like this.

ParentObject.ChildObject.Variable = Value;

friends.bill.firstname = "bill";

the key is looking at all of the Child-Objects values, for any child object that is in the Parent-Object. More specifically it's looking for any child-object associated to friends, and when you have the if statement (below) it will search for the variable in the child-object:

if(friends[key].firstName === name) {

So really, there are only 2 'key's in the Parent-Object "friends". And you can further expand on each of those child objects with the if statement, it wasn't clear and this is something that had me a little befuddled as well for a length of time..


#5

I am still struggling with this but I am hoping at least to get one bit.

From looking at the code over again, is friends[key] the entire block of code for friends.bill or friend.steve?

friends.bill = {
firstName: "Bill",
lastName: "Gates",
number: "(555) 555-5555",
address: ['One Microsoft Way','Redmond','WA','98052']
};

or this:

friends.steve = {
firstName: "Steve",
lastName: "Jobs",
number: "(222) 222-2222",
address: ['One Apple Drive', 'Cupertino', 'CA', '92351']
};