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

146
Vistas
Javascript - How to check the value of an array using a variable as the key

Let's say I have a simple array like this:

const arr = {
    name: 'Lorem',
    age: 'Ipsum',
}

How would I check the value of name based on a variable that is, for example, set on click of a button? Here's what I tried:

const arr = {
    name: 'Lorem',
    age: 'Ipsum',
}

$('button').click(function(e) {
  e.preventDefault();
  var key = $(this).attr('data-key');
  // this:
  console.log(arr.key);
  // should return the same result as this:
  console.log(arr.name);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-key="name">Click Me</button>

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Using the bracket notation:

const arr = { name: 'Lorem', age: 'Ipsum' };

$('button').click(function(e) {
  e.preventDefault();
  const key = $(this).attr('data-key');
  console.log(arr[key]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-key="name">Click Me</button>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Arr.key takes the keyword "key" Literally, and does not replace your variable in with the key name. You need to add brackets like so to perform this action:

arr[key];

Doing it this way will replace the literal term "key" with the variable you have assigned to it.

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