Tutorial :Associative Arrays/Object - getting values with dot notation



Question:

I don't really get why this isn't working:

thing = {  img78:{ exifmanufacturer:"Canon", exifmodel:"Canon EOS 450D", exifexposuretime:"1/125", exiffstop:"71/10", exifiso:"200"},  img79:{ exifmanufacturer:"Canon", exifmodel:"Canon EOS 550D", exifexposuretime:"1/125", exiffstop:"71/10", exifiso:"100"},  img80:{ exifmanufacturer:"Canon", exifmodel:"Canon EOS 550D", exifexposuretime:"1/30", exiffstop:"16/1", exifiso:"250"},  img81:{ exifmanufacturer:"NIKON CORPORATION", exifmodel:"NIKON D700", exifexposuretime:"10/600", exiffstop:"71/10", exifiso:"800"},  img82:{ exifmanufacturer:"NIKON CORPORATION", exifmodel:"NIKON D700", exifexposuretime:"10/2500", exiffstop:"90/10", exifiso:"800"},  img83:{ exifmanufacturer:"NIKON CORPORATION", exifmodel:"NIKON D700", exifexposuretime:"10/600", exiffstop:"71/10", exifiso:"800"},  img77:{ exifmanufacturer:"Canon", exifmodel:"Canon EOS 450D", exifexposuretime:"1/160", exiffstop:"8/1", exifiso:"100"},  img69:{ exifmanufacturer:"NIKON CORPORATION", exifmodel:"NIKON D700", exifexposuretime:"10/600", exiffstop:"71/10", exifiso:"800"}  };     var imageid = 'img80';    console.log('myVar1: ', thing.img80.exifmodel);  console.log('myVar2: ', thing.imageid.exifmodel);  

Outputs:

myVar1: Canon EOS 550D  thing.imageid is undefined  

I would have thought it would be the other way round.


Solution:1

You need to access it slightly differently using [] notation, like this:

console.log('myVar2: ', thing[imageid].exifmodel);  

In JavaScript these are equivalent:

obj.Property  obj["Property"]  

Or as in your case:

var prop = "Property";  obj[prop];  


Solution:2

In the second example, it'd be like writing thing.'img80'.exifmodel which is illegal. If you want to use a string to access a field of an object you'd have to do thing[imageid].exifmodel.


Solution:3

When you have the index in a string like that, you have to use the bracket notation to access the value:

var imageid = 'img80';  console.log('myVar2: ', thing[imageid].exifmodel);  

Or you could always take the eval (or evil, depending on how bad you consider this practice) route:

eval("console.log('myVar2: '), thing." + imageid + ".exifmodel)");  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »