从 JSON 数据创建两个依赖 select 列表

Create two dependent select lists from a JSON data

我正在尝试创建两个从属列表,它们的值是从 JSON 变量中提取的。

数据格式如下:

{
      "Name1": [
        {
          "Name1_Nickname": "ID1"
        }
      ],
      "Name2": [
        {
          "Name2_Nickaname": "ID2"
        }
      ],
      "Name3": [
        {
          "Name3_Nickname1": "ID3_1"
        }, {
          "Name3_Nickname2": "ID3_2"
        }
      ]
    }

如您所见,我正在处理 Map<String,List<Map<String,String>>>,我将其解析为 json 对象。我正在尝试找到一种方法来创建包含所有 Name1、Name2、Name3 的第一个选择列表,并根据我们选择的名称创建第二个带有 Name1_Nickname 的选择列表,例如,如果我们选择 Name1 和 Name3_Nickname1 , Name3_Nickname2 如果我们选择 Name3

遍历您的对象并根据该对象设置 select 选项非常简单。然后您将需要一个事件处理程序来处理第一个 select.

的更改

var items = {
      "Name1": [
        {
          "Name1_Nickname": "ID1"
        }
      ],
      "Name2": [
        {
          "Name2_Nickaname": "ID2"
        }
      ],
      "Name3": [
        {
          "Name3_Nickname1": "ID3_1"
        }, {
          "Name3_Nickname2": "ID3_2"
        }
      ]
    };

var one = document.getElementById("one");
var two = document.getElementById("two");

//loop the properties to build the first select
for(var prop in items) {
  var option = new Option(prop, prop);
  one.appendChild(option);
}

//add event handler on the first
one.addEventListener("change", function(e) {
  var value = e.target.value;
  
  //clear the second
  for(var i = two.options.length; i > 0; i--) {
    two.options[i - 1].remove();
  }
  
  //append items to the second
  items[value].forEach(function(item) {
    for (var itemProp in item) {
      var option = new Option(itemProp, item[itemProp]);
      two.appendChild(option);
    }
  });
  
});

//force a change event to set the second dropdown to the default
var changeEvent = new Event('change');
one.dispatchEvent(changeEvent);
<select id="one"></select>
<select id="two"></select>