Undefined fields in friends


#1

When I run the following code, I get undefined for all fields inside a friend (e.g. firstName, lastName, number). But I can't see how I'm populating them incorrectly...

var friends = {
bill: {
firstName: "Steve",
lastName: "Jobs",
number: 98
},
steve: {
firstName: "Steve",
lastName: "Borg",
number: 0
}
}
friends.bruce = {
firstName: "Bruce",
lastName: "Lee",
number: 1
};
friends.woz = {
firstName: "Steve",
lastName: "Wozniak",
number: -1
};

var list = function(friendList) {
for (var person in friendList) {
console.log(person);
}
}
list(friends);
console.log("Stage 1 done");

var search = function() {
for (var person in friends) {
console.log(person);
console.log(person["firstName"]);
console.log(person.firstName);
console.log(person.lastName);
console.log(person.number);
}
}

search();
console.log("*********** Last line ******************");


#2

Shorter version that fails same way (outputs "bill" and "undefined" before "Done"):

var friends = {
bill: {
firstName: "Bill"
}
}

var list = function(friendList) {
for (var person in friendList) {
console.log(person);
console.log(person.firstName);
}
}
list(friends);
console.log("******************* Done **************************");


#3

There is one bracket that is used mistakenly, i just cant find it quick. It says that in the error.


#4

No, that wasn't the problem. It's that the for loop is looping over indices rather than the actual objects themselves.

My shorter example above works if I replace "console.log(person.firstName);" with "console.log(friendList[person].firstName);".


#5

Don't forget you are calling on the "friends" object, and bill is a key within that

console.log(friends[person].firstName);

#6

Yup, agreed, thanks b4x!