Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

97
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda