javascript - 访问 .JSON 文件中的特定对象并创建选择菜单
问题描述
我正在使用从 .JSON 文件传递的数据创建选择菜单,但是我的 .JSON 文件有 2 个数组,我需要传递唯一的 country[] 数组。我写了一些代码,但它不起作用。有什么帮助吗?
我的 .JS 文件
let dropdown = document.getElementById("listCountry");
dropdown.length = 0;
let deafultOption = document.createElement('option');
deafultOption.text = 'Countries';
dropdown.add(deafultOption);
dropdown.selectedIndex = 0;
fetch('fleet.json')
.then(
function(response) {
if (response.status !== 200) {
console.warn('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
let option;
for (let i = 0; i < data.length; i++) {
option = document.createElement('option');
option.text = data[i].name;
option.value = data[i].abbreviation;
dropdown.add(option);
}
});
}
)
.catch(function(err) {
console.error('Fetch Error -', err);
});
我的 .JSON 文件
{
"country": [
{ "id": 1, "name" : "England" },
{ "id": 2, "name" : "Holland" },
{ "id": 3, "name" : "France" },
{ "id": 4, "name" : "Russia" }
],
"ship": [
{ "id": 1, "name": "Greenwich", "speed" : 12, "country_id" : 1 },
{ "id": 2, "name": "Eendracht", "speed" : 22, "country_id" : 2 },
{ "id": 3, "name": "Kingfisher", "speed" : 10, "country_id" : 1 },
{ "id": 4, "name": "Fury", "speed" : 12, "country_id" : 1 },
{ "id": 5, "name": "Hercule", "speed" : 33, "country_id" : 3 },
{ "id": 6, "name": "Licorne", "speed" : 33, "country_id" : 3 },
{ "id": 7, "name": "Arkhangel Gavriil", "speed" : 44, "country_id" : 4 }
]
}
也许我无法表达我的问题,这就是我用下图演示的原因。
解决方案
您需要遍历data.country
. 把它放在你有的地方response.json().then()
。
response.json().then(function(data) {
let option;
const countries = data.country;
// Array.prototype.forEach() iterates over all values in an array
countries.forEach(cont => {
option = document.createElement('option');
option.text = cont.name;
dropdown.add(option);
});
});
推荐阅读
- java - 为什么这个代码线程是安全的?我认为变量 testValue 是由不同的线程更新的?
- r - 如何创建一个函数来输出一个向量的每一行中有多少个字符包含在另一个向量中?
- docker - 控制 pod 的容器 IO 优先级
- ios - 重新加载数据时如何将 indexPath.row 值重置为零?
- javascript - 无法按类名定位输入字段
- javascript - Restful API:如何在 Node/Express 应用程序中显示特定数据?
- python - itertools.product 批量
- terraform-provider-gcp - Google 存储桶的 IAM 政策:google_storage_bucket_iam_binding 与 google_storage_bucket_iam_member
- python-2.7 - 我如何给 __init__ 它想要的参数?
- apache-storm - 是否有任何 Java API 可以知道拓扑何时准备好从 Spout 读取第一条消息