Search code examples
javascriptarraysfor-loopelementgetelementsbyname

For loop array set element equal to a variable


In the application a csv or xlsx file is parsed and the user then selects which fields represent an address.

Field Selection

After that I put the entire csv into an array and start to loop through it to send the address to be geocoded. The issue that I am having is that I need a way to set the array element equal to the field the user selected.

Before I loop through the array I grab the selection from each of the dropdowns like so.

var address_selection = document.getElementsByName("address1")[0].value;
var address2_selection = document.getElementsByName("address2")[0].value;
var city_selection = document.getElementsByName("city")[0].value;
var state_selection = document.getElementsByName("state")[0].value;
var postalcode_selection = document.getElementsByName("postalcode")[0].value;

My current code is setup like this, which hard codes the variable equal to a specific element.

for (i = 0; i < output.length; i++) {
        var id = output.ID;
        var address = output[i].Address;
        var address2 = output[i].Address2;
        var city = output[i].City;
        var state = output[i].StateProvince;
        var postalcode = output[i].ZipPostalcode;

What I need to do is somehow keep the variable names the same but change the element based on the user selection. I have tried something like this but it does not work.

var address = ("output[i]." + address_selection);

Solution

  • You can reference array indexes and object properties using [] notation, so in JS, this is very easy.

    In your case, it looks like output is an array of objects, so output[i] is an object with fields like Address, Address2 etc. Instead of writing output[i].Address you can write it as output[i]["Address"]. Furthermore, "Address" can be replaced with a variable just like i.

    With that in mind, and assuming the values of the options in your dropdownlists are things like "Address" and "Address2" then you should just be able to write this:

    var address_selection = document.getElementsByName("address1")[0].value;
    var address2_selection = document.getElementsByName("address2")[0].value;
    var city_selection = document.getElementsByName("city")[0].value;
    var state_selection = document.getElementsByName("state")[0].value;
    var postalcode_selection = document.getElementsByName("postalcode")[0].value;
    
    for (i = 0; i < output.length; i++) {
        var id = output.ID;
        var address = output[i][address_selection];
        var address2 = output[i][address2_selection];
        var city = output[i][city_selection];
        var state = output[i][state_selection];
        var postalcode = output[i][postalcode_selection];