1

How do I find an existing declared array or variable after I get the value of a data attribute?

For example

var myArray = [{a: 50, b: 70}, {a: 80, b: 90}],
    mySecondArray = [{a: 30, b: 20}, {a: 80, b: 40}];

$('.button').click(function() {
    var newArray = $(this).data('value'); // this will be a string depending on the value of any .button i clicked on <div data-value='myArray'></div>

    doSomething(newArray);
};

How do I use HTML 5 attribute to find an existing array and do something to it?

Kara
  • 6,115
  • 16
  • 50
  • 57
user2245534
  • 115
  • 6

2 Answers2

1

I would suggest making an object with the two arrays as properties. This makes it easy to lookup the array that you want.

 var arrays = {
     myArray:[{a: 50, b: 70}, {a: 80, b: 90}],
     mySecondArray:[{a: 30, b: 20}, {a: 80, b: 40}]
 }

 $('.button').click(function() {
     var newArray = $(this).data('value'); 

     doSomething(arrays[newArray]);
  };
Vincent Ramdhanie
  • 102,349
  • 23
  • 137
  • 192
0

You can't (without deprecated hacks).

However, you can store your accessible data in a map

var data = {myArray: [...], mySecondArray: [...]}; 

and look the values up via

doSomething(data[$(this).data('value')]);

Example:

var myArray = [{a: 50, b: 70}, {a: 80, b: 90}],
    mySecondArray = [{a: 30, b: 20}, {a: 80, b: 40}];

var data = {myArray, mySecondArray};

$('.button').click(function() {
    var newArray = $(this).data('value');
    
    //console.log(window[newArray]); // hack - don't do it
    //console.log(eval(newArray));   // hack - don't do it
    console.log(data[newArray]);     // good
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button" data-value="myArray">Click</button>

Why not window[newArray]? Because it only allows lookup of variables declared via var in global scope.

Why not eval(newArray)? See Why is using the JavaScript eval function a bad idea?

le_m
  • 19,302
  • 9
  • 64
  • 74