1

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>

2
  • 3
    arr[key] Also, that is an object, not an array. Commented Aug 12, 2021 at 21:34
  • @iz_ thank you for both! Commented Aug 12, 2021 at 21:35

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.