views:

33

answers:

3

Hi,

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.

Thanks.

+2  A: 

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];
Nick Craver
maybe a period between `[imageid].exifmodel`?
quixoto
@quixoto - Woops, good catch, thanks and updated :)
Nick Craver
ah... 'thing[imageid].exifmodel' I'd been trying all sorts of combos with square brackets and dots but not that one. Thanks!
xgarb
@xgarb: be sure you understand why that combination works before you dash off to the next thing-- it will serve you well down the road :)
quixoto
A: 

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.

carnold
A: 

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)");
Justin Niessner