如何遍历数组中的特定键值对

时间:2019-09-19 22:00:25

标签: javascript arrays json iteration key-value

我正在使用由250多个数组(与不同国家/地区有关的数据,例如人口,语言,货币等)组成的JSON对象,我需要从每个数组中提取特定的键值对(国家/地区代码)并存储在其他变量中,以便以后使用。

我尝试使用forEach方法,但是我没有太多的经验,因此没有成功。在搜寻了类似的问题之后,我发现人们通常会问如何遍历所有键/值对,而不是像这种情况下的特定对。

$.getJSON("https://restcountries.eu/rest/v2/all", function(callback) { 
    var isoCode = callback[5].alpha2Code;
    console.log(isoCode);
});

上面的代码提取特定数组的alpha2code(国家代码)(在此示例中为[5])。这是目标,但我需要以某种方式使该过程自动化,以使其遍历所有250个数组,提取所有国家/地区代码并将其存储在单独的变量中。

1 个答案:

答案 0 :(得分:3)

示例1

尝试类似的事情:

$.getJSON("https://restcountries.eu/rest/v2/all", function (data) {
    const codes = data.map(item => item.alpha2Code);
    console.log(codes); // ['AF', 'AX', '...']
});

以上代码均使用jQuery-成熟的JS库


示例#2

相同的场景,但是以现代方式,它使用基于Promise的Fetch API,如下所示:

fetch("https://restcountries.eu/rest/v2/all")
    .then((response) => {
        // Parse string to JS object
        return response.json();
    })
    .then((data) => {
        const codes = data.map(item => item.alpha2Code);
        console.log(codes); // ['AF', 'AX', '...']
    });

示例#3

清洁代码版本如下所示:

const config = {
    countriesUrl: "https://restcountries.eu/rest/v2/all"
};

async function makeRequest(url) {
    const response = await fetch(url);
    return response.json();
}

function fetchCounties() {
    return makeRequest(config.countriesUrl);
}

async function main() {
    try {
        const countries = await fetchCounties()
        const codes = countries.map(item => item.alpha2Code);
        console.log(codes); // ['AF', 'AX', '...']
    } catch (err) {
        console.error(err);
    }
}

main();