【问题标题】:fetch() from url, cant access object, console.log() works从 url 获取(),无法访问对象,console.log()有效
【发布时间】:2021-09-28 01:32:44
【问题描述】:

我有以下 3 行代码:

const response = await fetch(`https://restcountries.com/v3/alpha/${countrycode}`);
let json = await response.json();
console.log("this is my json file: ", json.borders)

问题是,当我这样做时,我在控制台日志中收到undefined,但我想访问对象的“边框”属性。 另一方面,如果我把第三行改成这样:

console.log("this is my json file: ", json)

我得到了如下所示的完整对象:

{"altSpellings": ["DE", "德意志联邦共和国", "Bundesrepublik Deutschland"], "area": 357114, "borders": ["AUT", "BEL", "CZE", "DNK", “FRA”、“LUX”、“NLD”、“POL”、“CHE”]、“capital”:[“Berlin”]、“cca2”: “DE”、“cca3”:“DEU”、“ccn3”:“276”、“cioc”:“GER”、“货币”: {"EUR": [Object]}, "demonyms": {"eng": [Object], "fra": [Object]}, “标志”:“????????”,“标志”:[“https://restcountries.com/data/deu.svg”, "https://restcountries.com/data/png/deu.png"], "idd": {"root": "+4", “后缀”:[数组]},“独立”:真,“内陆”:假, “语言”:{“deu”:“德语”},“latlng”:[51, 9],“名称”:{“common”: “Germany”、“nativeName”:[对象]、“official”:“Federal Republic of Germany"}, "region": "Europe", "status": "officially-assigned", “次区域”:“西欧”,“tld”:[“.de”],“翻译”:{“ces”: [对象],“deu”:[对象],“est”:[对象],“fin”:[对象],“fra”: [对象],“hrv”:[对象],“hun”:[对象],“ita”:[对象],“jpn”: [对象],“kor”:[对象],“nld”:[对象],“per”:[对象],“pol”: [对象],“por”:[对象],“rus”:[对象],“slk”:[对象],“spa”: [对象],“swe”:[对象],“urd”:[对象],“zho”:[对象]}, "unMember": true}

我该怎么做才能访问所有这些值,或者就像我的示例中的 'borders' 一样,我在这里做错了什么?

【问题讨论】:

    标签: javascript react-native


    【解决方案1】:

    响应是Array,而不是Object。将第 3 行更改为此以访问该属性。

        console.log("this is my json file: ", json[0].borders)
    

    【讨论】:

      猜你喜欢
      • 2016-11-05
      • 2021-11-29
      • 2021-07-02
      • 1970-01-01
      • 1970-01-01
      • 2018-01-06
      • 2019-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多