Contact List Question


#1

Hello all, I have already finished the exercise up to 8/8. Below is the code I have modified to make it look nicer. Any other suggestions to produce the same output will be appreciated as well.

However, I can't help wondering why is it that the code doesn't work if I change, for example

friends[contacts].address

to

friends.contacts.address

I am still confused about interpreting the "[]" and "." in the context of objects and arrays. Will very much appreciate it if anyone can explain this!


var friends = {};
friends.bill = {
  firstName: "Bill",
  lastName: "Gates",
  number: "(206) 555-5555",
  address: ['One Microsoft Way','Redmond','WA','98052']
};
friends.steve = {
  firstName: "Steve",
  lastName: "Jobs",
  number: "(408) 555-5555",
  address: ['1 Infinite Loop','Cupertino','CA','95014']
};

var list = function(contactList) {
  for(var contacts in contactList) {
    console.log("First Name: " + friends[contacts].firstName); 
      console.log("Last Name: " + friends[contacts].lastName); 
      console.log("Number: " + friends[contacts].number);
      console.log("Address: " + friends[contacts].address);
  }
};

var search = function(name) {
  for(var contacts in friends) {
    if(friends[contacts].firstName === name) {
      console.log("First Name: " + name); 
      console.log("Last Name: " + friends[contacts].lastName); 
      console.log("Number: " + friends[contacts].number);
      console.log("Address: " + friends[contacts].address);
    }
  }
};

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


#2

Start by not asking this question of others, but of yourself. It is your future, after all.


#3

Thank you for the swift reply.

Yes, I was able to complete the task for this section. But I was only able to do so because I referred to the example given and just followed, which allowed my code to work for the part "friends[contacts].address". But remembering the explanation that for example, "myObj.name" is also a shorthand for "myObj[name]", my understanding is that it should also be interchangeable for "friends[contacts].address" and "friends.contacts.address".


#4

ah, yes, confusing isn't it? thanks to your for loop contacts is now a string. so you need to use associative array notation ([]). Read this to clarify a thing or two.

anyway, because contacts is now a string, you would get this:

friends."contacts".adress

which is not working


#5

"Does your reply improve the conversation in some way? Be kind to your fellow community members."


#6

Hey, I thought I was being kind. I took the posted code to imply there was a much broader understanding than was evidenced in the question. The OP didn't respond, only flagged it. We could easily have discussed his search findings. I think I've taken enough flack for this error in judgement.


#7

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