如何遍历数组中的特定键值对
How to iterate through a specific key-value pair in array
我正在使用一个包含 250 多个数组的 JSON 对象(与不同国家相关的数据,如人口、语言、货币等)。我需要一个特定的键值对(国家代码)来从每个数组中取出并存储在不同的变量中,以便我以后可以将其用于其他用途。
我尝试过使用 forEach 方法,但我没有太多的经验,所以我没有成功。在谷歌搜索类似问题后,我发现人们通常会问如何遍历所有 key/value 对,而不是像本例中那样的特定一对。
$.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
Clean Code 版本 看起来像:
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();
我正在使用一个包含 250 多个数组的 JSON 对象(与不同国家相关的数据,如人口、语言、货币等)。我需要一个特定的键值对(国家代码)来从每个数组中取出并存储在不同的变量中,以便我以后可以将其用于其他用途。
我尝试过使用 forEach 方法,但我没有太多的经验,所以我没有成功。在谷歌搜索类似问题后,我发现人们通常会问如何遍历所有 key/value 对,而不是像本例中那样的特定一对。
$.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
Clean Code 版本 看起来像:
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();