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?

0

2 Answers 2

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]);
  };
Sign up to request clarification or add additional context in comments.

Comments

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?

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.