我正在使用一个由 250 多个数组组成的 JSON 对象(与不同国家/地区相关的数据,如人口、语言、货币等)。我需要从每个数组中提取特定的键值对(国家/地区代码)并存储在不同的变量中,以便稍后我可以将其用于其他用途。
我尝试过使用 forEach 方法,但我没有太多经验,所以我没有成功。在谷歌上搜索类似的问题后,我发现人们通常会问如何迭代所有键/值对,而不是像本例中那样迭代特定的键/值对。
$.getJSON("https://restcountries.eu/rest/v2/all", function(callback) {
var isoCode = callback[5].alpha2Code;
console.log(isoCode);
});
上面的代码提取特定数组(本例中为 [5])的 alpha2code(国家/地区代码)。这是目标,但我需要以某种方式自动化该过程,以便它遍历所有 250 个数组,提取所有国家/地区代码并将它们存储在单独的变量中。
最佳答案
示例#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();
关于javascript - 如何迭代数组中的特定键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58019399/