Khadijah Celestine Khadijah Celestine - 4 months ago 8
Javascript Question

How to access array if I get the name of the array from a selected option?

I have a list of items:

<select id ="listSelector">
<option value="books">Books</option>
<option value="countries">Countries</option>
<option value="states">States</option>
<option value="presidents">Presidents</option>
</select>


Which correspond to arrays of items:

var books = ['genesis', 'exodus', 'leviticus', 'numbers'];
var countries = ['Akrotiri','Albania','Algeria','American'];
var states = ['Alabama','Alaska','Arizona','Arkansas'];
var presidents = ['Washington','Adams','Jefferson','Madison'];


I want to be able to select an item from the list and use the value of the item to select the correct array.

var listSelector = document.getElementById('listSelector');
var selectedList = listSelector.options[listSelector.selectedIndex].value;
console.log('selected', selectedList[0]);
// returns first letter of the value of the list that was selected
// instead of the first item in the array.
// Ex. If I selected the Books option, the value would be 'books'
// and I want to access the books array.

Answer

If you change the structure to an object instead, it would be quite easy

var stuff = {
  books      : ['genesis', 'exodus', 'leviticus', 'numbers'],
  countries  : ['Akrotiri', 'Albania', 'Algeria', 'American'],
  states     : ['Alabama', 'Alaska', 'Arizona', 'Arkansas'],
  presidents : ['Washington', 'Adams', 'Jefferson', 'Madison']
}

var listSelector = document.getElementById('listSelector');

listSelector.addEventListener('change', function() {

  var item_array = stuff[listSelector.value];
  document.getElementById('result').innerHTML = '<pre>' + JSON.stringify(item_array, 0, 4) + '</pre>';
  
}, false);
<select id="listSelector">
  <option value="books">Books</option>
  <option value="countries">Countries</option>
  <option value="states">States</option>
  <option value="presidents">Presidents</option>
</select>

<div id="result"></div>