Ben
Ben

Reputation: 1022

Converting javascript string to code without using eval

I'm trying to do the below without using eval() as so many posts say it's slow and evil so you shouldn't use it as there's always alternative ways.

The JS (note i'm using jquery)

$('a').click(function() {

//Assign myVar to the id value of the a tag 
var myVar = $(this).attr('id');


$.getJSON("assets/js/json.js", function(json) {
    alert("json."+myVar+".thumb");
    }); 

});

And i have some basic html, which passing in the value for myVar

<a id="imageID1" href="#">A link 1</a><br />
<a id="imageID2" href="#">A link 2</a>

Basic JSON file

   {
"imageID1" : {
    "thumb" : "assets/images/312px.png",
    "zoomThumb" : "assets/images/gallery/_AR_0063_m_thumb.jpg",
    "large" : "assets/images/gallery/_AR_0063.jpg"
},

 "imageID2" : {
    "thumb" : "another.png",
    "zoomThumb" : "assets/images/gallery/_anotherb.jpg",
    "large" : "assets/images/gallery/another.jpg"
}

  }

So the ID for each link is passed to myVar on click, this is working fine but the alert value isn't correct.

For example if imageID2 is click the alert should actually display "another.png" but instead it's displaying the code i actually want to run, "[email protected]".

Now i can change the alert line to

   alert(eval("json."+myVar+".thumb"));

Which does the trick, but as mentioned don't want to use eval due to the know issues.

So any alternative way of doing the above. Thanks in advance for any help or tips.

Ben

Upvotes: 0

Views: 2013

Answers (2)

JoshNaro
JoshNaro

Reputation: 2097

This should work, I believe: alert(json[myVar].thumb);

Upvotes: 1

SLaks
SLaks

Reputation: 887451

You're trying to write

alert(json[myVar].thumb);

Indexer notation can be used to retrieve a property by name at runtime.

Upvotes: 4

Related Questions