What is wrong with my for...in loop? / How to reference object names? (codecademy, javascript)

398 Views Asked by At
var friends = {
    bill: {
        firstName: "Bill",
        lastName: "Gates",
        number: "(206) 555-5555",
        address: ['One Microsoft Way','Redmond','WA','98052'],
    },

    steve: {
        firstName: "Steve",
        lastName: "Jobs",
        number: "(408) 555-5555",
        address: ['1 Infinite Loop','Cupertino','CA','95014']
    }
};



var list = function(friends) {
    for (var i in friends) {
        console.log(friends[i]);
    }
};

I'm asked to log the names of the two objects to the console, but I'm confused about how to do this. Codecademy doesn't make it clear enough for me to understand. Can you? Desired output:

bill
steve

note: i do NOT want friends[i].firstname, I want the names of the objects friends[i].

3

There are 3 best solutions below

0
tckmn On

It should be:

for (var i in friends) {
    console.log(i);
}

This is because for...in loops through the keys of the object.

Also, I suggest a different variable name, such as friend instead of i, because i usually means a number or index.

0
JaredPar On

In this case i itself is the property name

for (var i in friends) {
  console.log(i);
}
0
thefourtheye On

You have to invoke the function list, like this

list(friends);

And in the list, you just have to print the name like this

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

In the ES5 supported implementations, you can simply use

Object.keys(friends);

If you use underscore.js, you can use _.keys, like this

_.keys(friends);