javascript - Why this variable is not an object? -


i have following object.

foobars = {     foo: {         propa: 1,         propb: 2     },     bar: {         propa: 3,         propb: 4     } }; 

i need loop though , compare properties of each of sub-object other variables. want check object has property doesn't work. tried use console.log understand , like:

for (foobar in foobars) {     if (foobars.hasownproperty(foobar)) {         console.log(foobar);                         //display 'foo' 'bar'         console.log(foobar.hasownproperty('propa')); //display 'false'          console.log(foobar.propa);                   //display undefined     } } 

jsfiddle

what wrong code? why don't foobar object can still access properties?

because foobar not object, (string) name of (one) property inside foobars object. when got string value represents name of property in object, can access property value (in case) foobars[foobar]

try

 console.log(foobars[foobar].hasownproperty('propa')); //display 'true'   console.log(foobars[foobar].propa);                   //display 1 3 

if not believe me type console.log(typeof(foobar)); , wee see type of foobar indeed string :)


Comments