How can I use an array key (text value) to reference a variable by that same name?
var cr,au,gen,bn,fmt,str;
var sbASCtrls = {"cr":"ContentRating","au":"Gold","gen":"Gender","bn":"Big Number","fmt":"Format","str":"Starting String"};
for (var key in sbASCtrls){
//This does not work ... breaks script
"'"+key+"'" = sbASCtrls[key];
alert('var CR: ' + cr);
return false;
}
In another language, I would simply surround the var name with percent signs, thus:
var %key% = "bob";
Would make:
var cr = bob;
How can this be done in javascript?
Why I require this unusual solution:
A series of AJAX calls are being made to a pre-existing PHP processor file that expects all data in HTML. In this case, I already had the data in JSON/jsObj format and wished to quickly break it out into separate variables. The most efficient/readable (believe it or not!) code was achieved by using eval()
. After reading Jonathan's and Niet's posts/comments, I struggled with how to keep the data in JSON format and use it like that, but the AJAX processor always requires one piece of data in HTML format. To my disappointment, I was unable to find a way to mix the two data types. Faced with the choice of re-coding the entire app to use JSON only, or moving ahead with HTML, the SDLC made the decision for me.
Thanks Niet, Jonathan, Cristy, Stephen Thomas and Fallenreaper for sound advice and great ideas. I'll be scoping other posts you've each made.