javascript - 如何根据所选值从 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>");
}
});
解决方案
您必须filter
在循环外使用并获取source[i]
选项中的值。
也只是.html()
用来清空。select
onchange
给你 => 工作演示: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>
推荐阅读
- postgresql - 需要多个客户的结果以及城市名称
- vue.js - 图像未在 vue 和 vue bootstrap 中显示
- javascript - 访问成员时对象数组返回未定义
- python - 根据另一行的值更改熊猫数据框中的一行
- selenoid - 有什么办法可以将 selenoid-ui 的默认端口从 8080 更改为其他端口
- saxon - 警告:无法识别的元素 xsl:variable online running saxon 但不在 Oxygen 中,为什么?
- arrays - 返回具有对象中某些属性的数组对象。打字稿
- c# - json反序列化中的日期时间字段
- android - 单击 Mapview 中的特定标记后,如何从 Firestore 数据库中获取有关活动的特定数据?
- testing - 导出脚本