7/8 Error: Oops, try again. It looks like your search function doesn't return contact information for Steve


#1

Hi all,

I'm having a headache with that part, here is my code:
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 = ["This", "Direction", "Is"];

friends.steve = new Object();
friends.steve.firstname = "Steve";
friends.steve.lastName = "Jobs";
friends.steve.number = "(307) 555-5555";
friends.steve.address = ["This", "Direction", "Is Not"];

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(friends[key]);
return friends[key];
}
}
};

list(friends);
search("Steve");

The output is:
bill
steve
{ firstName: 'Bill',
lastName: 'Gates',
number: '(206) 555-5555',
address: [ 'This', 'Direction', 'Is' ] }

Please explain me more about what is "key" doing.

Thanks in advance,


#2

key is a variable name. which could be any term, but is aptly named for what function it performs--act as a key (property name) reference.

The for..in statement iterates over object properties one key:value pair at a time.

Let key equal 'bill'

var key = 'bill'
console.log(key); // bill
console.log(friends[key]); // { firstName: ... }

Same as,

console.log(friends['bill']);

JavaScript objects are Associative Arrays in that they have a string index, with each index associated with a value. This is the subscript form of a key: value pair.

friends.bill.firstName  =>  friends['bill'].firstName