2

I've got what I'm assuming is a fairly simple javascript problem, but it's baffling me. Basically, I'm unable to access the properties inner properties of nested object literals within a for loop. I'd love if someone oculd explain to me why this doesn't work:

var object = {

        "foo":{
            propertyOne : "One",
            propertyTwo : "Two"
            },
        "bar":{
            propertyOne : "Three",
            propertyTwo : "Four"
        }

    };

    //This correctly returns "One"
    window.alert(object.foo.propertyOne);

    for(var m in object)
    {
        //this returns foo followed by bar
        window.alert(m);
        //This returns undefined
        window.alert(m.propertyOne);
    }

I think this illustrates the problem well enough. Why do I get undefined when I try to access the properties of the inner objects within the loop? I assume I'm missing something really simple here.

Thanks for reading.

DoonStar
  • 35
  • 5

3 Answers3

3

This is because m in your for loop is a key name (a string). You can use it to access the actual value that is referenced by that key:

for(var m in object)
{
        // This returns 'foo' followed by 'bar'
        console.log(m);

        // returns 'string'
        console.log(typeof m);

        // This returns the value referenced under the 'm' key
        console.log(object[m]);

        // Since we know the value is an object with a `propertyOne` key..

        // This returns a value from the object which is referenced by the 'm' key
        console.log(object[m].propertyOne);
}
Dominic
  • 62,658
  • 20
  • 139
  • 163
0

it should be

for(var m in object)
{
    window.alert(m);
    window.alert(object[m].propertyOne); 
}

m is the key name it doesn't have the properties, you need to use this key name to get value from the object and then read that value's property propertyOne.

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

The for..in loop iterates over property names of an object. See the documentation on MDN - for..in

From the MDN article on Objects, a property name can be defined as:

...any valid JavaScript string, or anything that can be converted to a string, including the empty string.

Because the property name is a string, it does not have any of the properties you defined in your object. However, you can use the property name to access the property in this manner:

for(var m in object) {
  window.alert(m);
  window.alert(object[m].propertyOne); 
}
gnerkus
  • 11,357
  • 6
  • 47
  • 71