Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How do you loop through an array of objects?

I have created an array of objects, and i'm trying to loop through each and store their key/value pairs in new variables. Yet, I'm only getting the last object in the array back when I log it out to the console - "jon"

any help would be great

Thanks

var userList = [
    {
        name: "anka",
        password: "H2X835"
    },
    {
        name: "bob",
        password: "bob"
    },
    {
        name: "jon",
        password: "jon"
    }
];

for (var i = 0; i < userList.length; i++) {
    users = userList[i].name;
    logIn = userList[i].password;
}

1 Answer

Hi,

This is because you are overwriting the variable each time you loop through.

If you 'console.log' the variables inside each loop, you can see that they are being set.

for (var i = 0; i < userList.length; i++) {
    users = userList[i].name;
    logIn = userList[i].password;
    console.log("user : "+users+" | pass : "+logIn);
}

It depends on what you want to do with them. I'm assuming whatever you do it will be within the loop, so you should be good to go.