Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

92
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda