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