Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

91
Views
How to make string act like a variable name?

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;
}
about 4 years ago ยท Juan Pablo Isaza
1 answers
Answer question

0

Specify the dictionary first

Then you can take id's object... ๐Ÿ™ƒ

const dictionary = {
    id1: {name: 'xxxx'},
    id2: {name: 'yyyy'},
    id3: {name: 'zzzz'},
};

const myfunc = (item)=>{
    const idName = item.id;
    const aName = dictionary[idName];
    console.log(aName.name);
};
<div id="id1" onclick="myfunc(this)">one</div>
<div id="id2" onclick="myfunc(this)">one but 2</div>
<div id="id3" onclick="myfunc(this)">the third</div>

about 4 years ago ยท Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!