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

object property undefined

Hi, I'm having trouble to understand an error in my JavaScript code. Here is my code :

tab = []

var objet = {
    var1: 1,
    var2: 2,
    var3: 3,
    var4: 4,
    var5: 5,
};

for (x in objet)
    tab.push(objet.x);

console.log(tab);

And here's the result : http://image.noelshack.com/fichiers/2015/36/1441435179-sans-titre.jpg

On the other hand, when I try to print object.var1 in the console, I get exactly the property for the value I asked, and when I print x at each step of the loop, I get the actual name of the property...

What's wrong with my code ?

2 Answers

To push that object to the array you need to use bracket notation

for (x in objet)
    tab.push(objet[x]);

When using for ... in .... loop to retrieve property value always use '[' ']' suffix.

tab = [];

var object = {
    var1: 1,
    var2: 2,
    var3: 3,
    var4: 4,
    var5: 5
};

var x;
for (x in object)
    tab.push(object[x]);

console.log(tab);

I forgot the exact reason but I'll look for it and update the answer, in the meanwhile just take it what it is or search for yourself.