【问题标题】:How to fetch JSON subcategories?如何获取 JSON 子类别?
【发布时间】:2021-12-21 13:33:21
【问题描述】:

我正在尝试从本地 JSON 文件中获取数据,这是目前为止的 JS 脚本

let accordion=document.querySelector('#accordion');
fetch('countries.json')
.then(function(response){
    return response.json();
})
.then(function(data){
    let continents=Object.keys(data);
    for(let i=0;i<continents.length;i++){
        let continent=continents[i];
        let heading=document.createElement('h3');
        heading.textContent=continent;
        accordion.appendChild(heading);
        let countries=data[continent];
        let ul=document.createElement('ul');
        for(let j=0;j<countries.length;j++){
            let country=countries[j];
            let li=document.createElement('li');
            li.textContent=country;
            ul.appendChild(li);
        }
        accordion.appendChild(ul);
    }
})

它的作用是显示数据“大陆”的标题和行数,但数组内部的任何内容(所有内容实际上)都显示为 [Object Object],所以我需要正确获取此数据以及数组对象中的数据。

【问题讨论】:

  • 类似li.textContent = country.name
  • 仅供参考,使用forEach() 编写这些循环会更容易。
  • 如果您需要更详细的帮助,您需要发布数据样本和所需结果。

标签: javascript arrays json fetch-api


【解决方案1】:

原来这是一个简单的解决方案... 正如 Bammar 所说,我错误地标记了我的数据

类似于 li.textContent = country.name

顺便说一句,国家实际上是回调大陆,所以这是固定的,通过 forEach 循环,我将获取国家数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多