Home > Net >  How to make string act like a variable name? [duplicate]
How to make string act like a variable name? [duplicate]

Time:10-08

I've seen many other questions like this but none of them helped in my case, I don't feel my question is duplicate for this reason. All questions regarding this case try to attach a new "meaning" to the string variable, while I already have those variables, just want to use a string to be able to reach those pre-existing variables.

I have few divs with IDs and few dictionaries in JS with the names being the same as those IDs. I want to take those IDs, which are returned as strings, and use them as variables to access those dictionaries.

I tried using window[item.id] = idName but I believe I don't understand it, as it doesn't work.

My code:

<div id="id1" onclick="myfunc(this)"></div>
<div id="id2" onclick="myfunc(this)"></div>
<div id="id3" onclick="myfunc(this)"></div>
/* pre-existing variables I want to be able to use with IDs taken from function*/
id1={"name":"xxxx"}
id2={"name":"yyyy"}
id3={"name":"zzzz"}
 
function myfunc(item){
idName=item.id//returns string with id name
name=idName["name"]//doesn't work, as idName is a string and doesn't behave as a variable name;
}

CodePudding user response:

Specify the dictionary first

Then you can take id's object...

  • Related