3

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
thesonglessbird
  • 570
  • 1
  • 7
  • 16

3 Answers3

7

If you're talking about the item1 part, you're looking for:

myValue = myTestObject["item1"];

No need for eval. (There almost never is.)

If you're talking about getting at the myTestObject variable using a "myTestObject" string, you want to refactor the code so you're not doing that, rather than using eval. Unfortunately the variable object used for symbol resolution within the function is not accessible directly. The refactor could just use an object explicitly:

var stringToObjectRef = function() {

    var objects = {};

    var myTestVar = "myTestObject";
    objects.myTestObject = { 'item1' : 100, 'item2' : 12, 'item4' : 18 };

    var myValue = objects[myTestVar].item1;

    alert(myValue);

}();

Off-topic, I don't recall precisely why, but if you're going to execute that anonymous function immediately like that, you need to put the function expression in parentheses:

var x = (function() { return 5; })();

rather than

var x = function() { return 5; }();

Again, I don't recall why, and whether it was because of an implementation bug in a popular interpreter or an actual requirement of the syntax.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Try this instead:

var stringToObjectRef = function() {
  var myTestObject = { 'item1' : 100, 'item2' : 12, 'item4' : 18 };
  var myValue = myTestObject['item1'];
  alert(myValue);
}();
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • I'm looking at optimising my code, so I want to remove all the eval() statements in my code. I'm 99.9% certain I don't need them. – thesonglessbird Apr 15 '10 at 10:22
0

eval("myTestObject[\"item1\"") should do the trick, as myTestObject.item1 is shorthand for myTestObject["item1"]

How do I reference an object dynamically?

Community
  • 1
  • 1
Axarydax
  • 16,353
  • 21
  • 92
  • 151