1

在应用程序中解析 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);
4

2 回答 2

1

您可以使用符号来引用数组索引和对象属性[],因此在 JS 中,这非常容易。

在您的情况下,它看起来像是output一个对象数组,一个具有诸如 等字段的对象也是如此。output[i]您可以将其写为.而不是编写。此外,可以用变量替换,就像.AddressAddress2output[i].Addressoutput[i]["Address"]"Address"i

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

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];
于 2017-10-06T12:20:19.513 回答
1
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]);
}
于 2017-10-06T12:34:56.427 回答