[英]How to iterate through a specific key-value pair in array
我正在使用一个 JSON object ,它由 250+ 个 arrays 组成(与不同国家相关的数据,如人口、语言、货币等)我需要提取每个数组和存储在国家/地区代码中的特定键值对)一个不同的变量,所以我以后可以用它做别的事情。
我尝试过使用 forEach 方法,但我没有很多经验,所以我没有成功。 在谷歌搜索类似的问题后,我发现人们通常会问如何迭代所有键/值对,而不是像这种情况下的特定键/值对。
$.getJSON("https://restcountries.eu/rest/v2/all", function(callback) {
var isoCode = callback[5].alpha2Code;
console.log(isoCode);
});
上面的代码提取了特定数组的 alpha2code(国家代码)(本例中为 [5])。 这是目标,但我需要以某种方式自动化该过程,以便它遍历所有 250 个 arrays,提取所有国家代码并将它们存储在单独的变量中。
尝试这样的事情:
$.getJSON("https://restcountries.eu/rest/v2/all", function (data) {
const codes = data.map(item => item.alpha2Code);
console.log(codes); // ['AF', 'AX', '...']
});
以上代码使用 jQuery —成熟的 JS 库。
相同的场景,但以现代方式,使用基于 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', '...']
});
清洁代码版本将如下所示:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.