我有以下代码:
function fetchDemo(url) {
return fetch(url).then(function(response) {
return response.json();
}).then(function(json) {
return json;
});
}
fetchDemo(countriesUrl).then(function(result) {
console.log(result);
});
fetchDemo(carMakesUrl).then(function(result2) {
var obj = {};
result2.forEach(function(ele) {
obj[ele.make_country] = (obj[ele.make_country] || 0) + 1
});
for (var country in obj) {
console.log(country + ", " + "produces the following number of cars: " + obj[country]);
}
});
countriesUrl = https://rawgit.com/csabapalfi/20d74eb83d0be023205225f79d3e7964/raw/7f08af5c0f8f411f0eda1a62a27b9a4ddda33397/countries.json
[
{
"name": "Afghanistan",
"code": "AF"
},
{
"name": "Åland Islands",
"code": "AX"
},
{
"name": "Albania",
"code": "AL"
},
{
"name": "Algeria",
"code": "DZ"
},
{
"name": "American Samoa",
"code": "AS"
},
{
"name": "AndorrA",
"code": "AD"
},
{
"name": "Angola",
"code": "AO"
},
{
"name": "Anguilla",
"code": "AI"
},
{
"name": "Antarctica",
"code": "AQ"
} ....
carMakesUrl = https://rawgit.com/csabapalfi/20d74eb83d0be023205225f79d3e7964/raw/7f08af5c0f8f411f0eda1a62a27b9a4ddda33397/carmakes.json
[
{
"make_id": "abarth",
"make_display": "Abarth",
"make_is_common": "0",
"make_country": "Italy"
},
{
"make_id": "ac",
"make_display": "AC",
"make_is_common": "0",
"make_country": "UK"
},
{
"make_id": "acura",
"make_display": "Acura",
"make_is_common": "1",
"make_country": "USA"
},
{
"make_id": "alfa-romeo",
"make_display": "Alfa Romeo",
"make_is_common": "1",
"make_country": "Italy"
},
{
"make_id": "allard",
"make_display": "Allard",
"make_is_common": "0",
"make_country": "UK"
},
{
"make_id": "alpina",
"make_display": "Alpina",
"make_is_common": "0",
"make_country": "UK"
},.....
每个数组都有一个对象列表,我如何匹配来自不同fetch的数组。
我想比较结果和结果2
答案 0 :(得分:1)
fetch工作异步,因此你必须堆叠fetch-requests。
fetchDemo(countriesUrl).then(function(result) {
var countries = result;
fetchDemo(carMakesUrl).then(function(result2) {
var obj = {};
result2.forEach(function(ele) {
obj[ele.make_country] = (obj[ele.make_country] || 0) + 1
});
for (var country in obj) {
console.log(country + ", " + "produces the following number of cars: " + obj[country]);
}
});
});
您有两个vars:countries
和result2
,您可以像往常一样进行比较(JavaScript - Compare two arrays)。