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

145
Views
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 answers
Answer question

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 Report

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 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!