Using a string as an object reference
Posted
by user317362
on Stack Overflow
See other posts from Stack Overflow
or by user317362
Published on 2010-04-15T10:17:39Z
Indexed on
2010/04/15
10:23 UTC
Read the original article
Hit count: 131
JavaScript
I currently have a Javascript function that uses a string to reference an object name and acces its properties. I'm currently using eval() to get the the desired effect which I know is very, very wrong. Here is an example of how I'm currently achieving what I want:
var stringToObjectRef = function() {
var myTestVar = "myTestObject";
var myTestObject = { 'item1' : 100, 'item2' : 12, 'item4' : 18 };
var myValue = eval(myTestVar + '.item1');
alert(myValue);
}();
I've tried using something like [myTestVar].item1, but this returns undefined. What is the correct syntax to achieve this?
Thanks in advance.
© Stack Overflow or respective owner