Skip to content

Instantly share code, notes, and snippets.

@trovster
Created August 26, 2015 10:31
Show Gist options
  • Save trovster/a30c20a0cbd0b2c5a01c to your computer and use it in GitHub Desktop.
Save trovster/a30c20a0cbd0b2c5a01c to your computer and use it in GitHub Desktop.
How can I get dynamic variable without eval?
<script type="text/javascript" id="bowling--js">
var bowling_options = [1,2,3,4,5];
</script>
<script type="text/javascript" id="restaurant--js">
var restaurant_options = ['a','b','c'];
</script>
$(['bowling', 'restaurant']).each(function (type) {
eval(type + '_options'); // how can I avoid this?
});
@rythie
Copy link

rythie commented Aug 26, 2015

You could do:

var options = {};
options.bowling = [1,2,3,4,5];
options.restaurant = ['a','b','c'];

$(['bowling', 'restaurant']).each( function (key, type) {
  console.log(options[type]);
});

or without jQuery:

['bowling', 'restaurant'].forEach(function (type) {
  console.log(options[type]);
});

@trovster
Copy link
Author

Thanks Rich. I have migrated the code to what you have suggested. Works :)

@rythie
Copy link

rythie commented Aug 26, 2015

great!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment