Issue
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;
}
Solution
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>
Answered By - Vadim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.