2

How can I use an array key (text value) to reference a variable by that same name?

jsFiddle

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.

cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • 1
    You'll have to use `eval()` if you really want to do this as JavaScript doesn't support dynamic identifiers otherwise. But, the [typical suggestion is to use an object instead](http://stackoverflow.com/questions/5117127/javascript-dynamic-variable-name), which you already have. So, why not keep it as an object and get/set the properties you want? – Jonathan Lonowski Mar 12 '14 at 18:44
  • I would not do this. Even if you managed to get it working, when it comes to publishing something publicly, minification makes it smaller and quicker to load on pages, so it isnt going to matter. – Fallenreaper Mar 12 '14 at 18:47

3 Answers3

4

While you could use eval like this:

// DO NOT DO THIS
eval(key+" = svASCtrls[key];");

You should probably stop and ask yourself why you want to do this in the first place. You already have a very tidy object, so just use it...

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Niet, I can see why you have 14 gold. Thanks very much for the helpful answer. Please see addendum to my question that explains why I required this unusual solution. In my case, after having read a number of cautions regarding `eval()`, I believe it to be the best solution in these circs. – cssyphus Mar 13 '14 at 18:09
1

You can define your variables as properties of an object

var obj = { cr: null, au: null, gen: null, bn: null, fmt: null, str: null };
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
    obj[key] = sbASCtrls[key];

    alert('var CR: ' + obj.cr);
    return false;
}
Stephen Thomas
  • 13,843
  • 2
  • 32
  • 53
1

As any global variable is a child of the window object, you can create the variable at window[key]

for (var key in sbASCtrls){
    alert("key: " + key);
    alert("val: " + sbASCtrls[key] );

    //This should work, but jsfiddle messes with the window object
    window[key] = sbASCtrls[key];


    alert('var CR: ' + cr);
    return false;
}

Note that this does not work on jsfiddle, but should work on your website.

XCS
  • 27,244
  • 26
  • 101
  • 151
  • 1
    This assumes they are global. And, they may be. But, you might want to emphasize that dependency. – Jonathan Lonowski Mar 12 '14 at 18:49
  • Although I chose Niet's `eval()` as the best answer to my question, this was a great answer! And it worked. And it answered the question that I asked. +1 Great solution, but not greater than [this other amazing post](http://stackoverflow.com/questions/12027161/css-realistic-shadows-light-source/12027417#12027417) you answered - another +1. – cssyphus Mar 13 '14 at 17:43