【问题标题】:How to iterate through a specific key-value pair in array如何遍历数组中的特定键值对
【发布时间】:2019-09-19 22:00:25
【问题描述】:

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

我尝试过使用 forEach 方法,但我没有很多经验,所以我没有成功。在谷歌搜索了类似的问题后,我发现人们通常会问如何迭代所有键/​​值对,而不是像本例中那样的特定键/值对。

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

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

【问题讨论】:

标签: javascript arrays json iteration key-value


【解决方案1】:

示例 #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();

【讨论】:

  • 这正是我想要完成的。感谢您向我展示现代解决方案 - 我需要研究的东西。谢谢
  • 没问题@Rogozin ;-) 当你刷新时,你会看到干净的代码版本。
  • 你也可以在 jQuery 中使用 Promise。 $.getJSON("...").then(data => data.map(item => item.alpha2Code))
  • 太棒了@3limin4t0r,但自 2015 年以来我们的浏览器中就有 Promise :)
  • 我的意思是,如果您已经在使用 jQuery,则在创建方法时无需重新发明轮子。当您可以简单地使用 let data = await $.getJSON("...") 时,没有理由创建自己的 $.getJSON 版本
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-06
  • 2020-02-22
  • 1970-01-01
  • 2020-10-02
  • 1970-01-01
  • 2017-05-26
  • 1970-01-01
相关资源
最近更新 更多