我正在使用由250多个数组(与不同国家/地区有关的数据,例如人口,语言,货币等)组成的JSON对象,我需要从每个数组中提取特定的键值对(国家/地区代码)并存储在其他变量中,以便以后使用。
我尝试使用forEach方法,但是我没有太多的经验,因此没有成功。在搜寻了类似的问题之后,我发现人们通常会问如何遍历所有键/值对,而不是像这种情况下的特定对。
$.getJSON("https://restcountries.eu/rest/v2/all", function(callback) {
var isoCode = callback[5].alpha2Code;
console.log(isoCode);
});
上面的代码提取特定数组的alpha2code(国家代码)(在此示例中为[5])。这是目标,但我需要以某种方式使该过程自动化,以使其遍历所有250个数组,提取所有国家/地区代码并将其存储在单独的变量中。
答案 0 :(得分:3)
尝试类似的事情:
$.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();