You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将选中的字符串数组项匹配对象键合并对应值用于联动下拉框

实现步骤

以下是基于原生JavaScript的实现方式,不需要额外框架依赖:

1. 编写基础HTML结构

先定义两个select元素,第一个开启多选属性:

<!-- 多选下拉框 -->
<select id="multiSelect" multiple>
  <option value="one">one</option>
  <option value="two">two</option>
  <option value="three">three</option>
</select>
<!-- 动态生成的结果下拉框 -->
<select id="resultSelect"></select>

2. 编写JS逻辑

首先定义你提供的数据源,再给多选下拉框绑定变更事件,每次选中值变化时自动合并对应数组并渲染到结果下拉框:

// 定义值到数组的映射对象
const optionMap = { 
  "one" : ['apple','orange','banana'], 
  "two" : ['cucumber','onion'], 
  "three" : ['potato','radish','carot']
};
// 获取两个下拉框的DOM节点
const multiSelect = document.getElementById('multiSelect');
const resultSelect = document.getElementById('resultSelect');
// 监听多选下拉框的选中变化事件
multiSelect.addEventListener('change', function() {
  // 获取所有选中的选项值
  const selectedKeys = Array.from(this.selectedOptions).map(option => option.value);
  // 合并选中值对应的所有数组
  const mergedList = selectedKeys.flatMap(key => optionMap[key] || []);
  // 清空结果下拉框的旧选项
  resultSelect.innerHTML = '';
  // 遍历合并后的数组生成新选项
  mergedList.forEach(item => {
    const opt = document.createElement('option');
    opt.value = item;
    opt.innerText = item;
    resultSelect.appendChild(opt);
  });
});

兼容说明

如果需要兼容不支持flatMap的旧浏览器,可以把合并数组的代码替换为:

const mergedList = [].concat(...selectedKeys.map(key => optionMap[key] || []));

内容的提问来源于stack exchange,提问作者salman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 14:57:00