首页 > 解决方案 > 访问 .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 }
    ]
}

也许我无法表达我的问题,这就是我用下图演示的原因。

在此处输入图像描述

标签: javascriptjsonapifetch

解决方案


您需要遍历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);
   });
});

推荐阅读