For循环数组设置元素等于一个变量

For loop array set element equal to a variable

在应用程序中解析 csv 或 xlsx 文件,然后用户选择哪些字段代表地址。

之后,我将整个 csv 放入一个数组中并开始遍历它以发送要进行地理编码的地址。我遇到的问题是我需要一种方法来将数组元素设置为等于用户选择的字段。

在遍历数组之前,我像这样从每个下拉列表中获取选择。

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;
        var address2 = output[i].Address2;
        var city = output[i].City;
        var state = output[i].StateProvince;
        var postalcode = output[i].ZipPostalcode;

我需要做的是以某种方式保持变量名称相同,但根据用户选择更改元素。我已经尝试过类似的方法,但它不起作用。

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

你可以使用[]符号引用数组索引和对象属性,所以在JS中,这很容易。

在您的例子中,output 看起来像是一个对象数组,因此 output[i] 是一个具有 AddressAddress2 等字段的对象。而不是写作 output[i].Address 你可以把它写成 output[i]["Address"]。此外,"Address" 可以像 i.

一样用变量替换

考虑到这一点,并假设下拉列表中选项的值是 "Address" 和 "Address2" 之类的东西,那么您应该可以这样写:

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];
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;
var myArray = {
    address_selection: address_selection,
    address2_selection: address2_selection,
    city_selection: city_selection,
    state_selection: state_selection,
    postalcode_selection: postalcode_selection
    };
for (var key in myArray) {
  console.log("key " + key + " has value " + myArray[key]);
}