首页 > 解决方案 > 如何根据所选值从 JSON 数组构建列表?

问题描述

我正在尝试根据所选媒体创建经过筛选的来源选择列表。我知道我在过滤器下面使用的方法,但没有正确显示列表。我半睡半醒,试图纠正这个问题,需要有人提供一些意见。:-) 干杯!

let types = [
  {
    "id": 1,
    "media": "TV",
    "source": "wkbw"
  },
  {
    "id": 2,
    "media": "TV",
    "source": "wffo"
  },
  {
    "id": 3,
    "media": "TV",
    "source": "wtrw"
  },
  {
    "id": 8,
    "media": "Radio",
    "source": "wrqa"
  },
  {
    "id": 9,
    "media": "Radio",
    "source": "wuqa"
  },
  {
    "id": 10,
    "media": "Radio",
    "source": "wzzt"
  }
]

$("#type").change(function() {
    $("#results").empty();
    selected = $("#type").val();
  
  for (var i = 0; i < types.length; i++) {
    // some kind of filter source by selected the one below isn't quite right
    // $("#results").append("<option value='" + types[i].source + "'>" + types[i].source + "</option>");
    source = types.filter(types => types.media === selected).map(d => d.source).join('');
    $("#results").append("<option value='" + source + "'>" + source + "</option>");
  }
});

这是我的小提琴:https ://jsfiddle.net/simplymarkb/sk0rdf2j/31/

标签: javascriptjson

解决方案


您必须filter在循环外使用并获取source[i]选项中的值。

也只是.html()用来清空。selectonchange

给你 => 工作演示:https ://jsfiddle.net/usmanmunir/u38hrox1/11/

只需运行代码片段即可查看它的作用。

let types = [
  {
"id": 1,
"media": "TV",
"source": "wkbw"
  },
  {
"id": 2,
"media": "TV",
"source": "wffo"
  },
  {
"id": 3,
"media": "TV",
"source": "wtrw"
  },
  {
"id": 8,
"media": "Radio",
"source": "wrqa"
  },
  {
"id": 9,
"media": "Radio",
"source": "wuqa"
  },
  {
"id": 10,
"media": "Radio",
"source": "wzzt"
  }
]

$("#type").change(function() {
  $("#results").html('')
  var selected = $("#type").val();
  var source = types.filter(types => types.media === selected).map(d => d.source);
  for (var i = 0; i < source.length; i++) {
    $("#results").append("<option value='" + source[i] + "'>" + source[i] + "</option>");
  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="type">
  <option value="TV">TV</option>
  <option value="Radio">Radio</option>
</select>
<hr>
<select id="results">..results</select>


推荐阅读