Archive for January, 2012

Iterating through properties of a JavaScript Object with the “For In” loop

Posted in Geekdom, Programing, Web Development on January 16th, 2012 by Jarred – Comments Off on Iterating through properties of a JavaScript Object with the “For In” loop

As I have mentioned before I am a novice self taught programmer and I often come across little problems that take me quite a while to figure them out. I like to post them here so I can come back and remember how I solved the problem and also so hopefully others can benefit from my struggles. I came access one of these said problems this weekend trying to iterate through a object in JavaScript using a “for in” loop. I understood the looping mechanism quite well, however getting the syntax to work for me through me for a loop.

 

Incorrect (This is how I would assume it would work)

 for (var x in someObject.someProperty)

{
newVar = someObject.someProperty.x.anotherProperty;
}

This is how I got it to work

 for (var x in someObject.someProperty)

{
newVar = someObject.someProperty[x].anotherProperty;
}

You will notice you cant use .x to access the property the loop is currently processing,  you must use the [x] In truth I do not understand why this is so if anybody out there cares to enlighten me that would be appreciated. Either way hopefully this might save some frustration.