Search code examples
javascriptdynamic-data

Convert string to variable in Javascript


Is there any way to convert a string to a variable in Javascript? Right now, what I have is a script that updates data based on the values of the select box:

<script type="text/javascript">
var a = new Array();
a[0] = 'Name';
a[1] = 'Description';

var b = new Array();
b[0] = 'Name 2';
b[1] = 'Description 2';

function changeSystem(){
    var selectedAccount=document.getElementById('selected_option').value;

    document.getElementById('name').innerHTML = selectedAccount[0];
    document.getElementById('description').innerHTML = selectedAccount[1];
}
</script>
<form method="POST">
    <select onchange="changeSystem()" id="selected_option">
     <option>A</option>
     <option>B</option>
    </select>
</form>
<span id="name"></span><br>
<span id="description"></span><br>

selectedAccount is the string of the chosen element in <select>. However, for it to access the array, it needs to be a variable, i.e. a[0] instead of 'a'[0]. What solutions are there to this?


Solution

  • var dict = {
        'A': ['Name', 'Description'],
        'B': ['Name 2', 'Description']
    };
    
    dict['A'][0]
    

    So dynamically access it with

    dict[selectedAccount][0]
    

    You can use an object literal instead of an array:

    var dict = {
        'A': {'name': 'john'}
    };
    
    dict['A']['name']