API呼叫代碼:
const settings = {
"async": true,
"crossDomain": true,
"url": "https://v3.football.api-sports.io/fixtures?date=2021-04-07",
"method": "GET",
"headers": {
"X-RapidAPI-Host": "v3.football.api-sports.io",
"X-RapidAPI-Key": "MY-API-KEY"
}
};
$.ajax(settings).done(function (response) { console.log(response)}); // Logs API Data, Need to Filter This
API 資料的格式為:
response: Array(305) [ {…}, {…}, {…}, … ]
??
[0…99]
??? //FIRST ELEMENT
0: Object { fixture: {…}, league: {…}, teams: {…}, … }
????
fixture: Object { id: 812523, timezone: "UTC", date: "2022-05-13T00:00:00 00:00", … }
?
goals: Object { home: null, away: null }
????
league: Object { id: 395, name: "Divizia A", country: "Moldova", … }
????
score: Object { halftime: {…}, fulltime: {…}, extratime: {…}, … }
????
teams: Object { home: {…}, away: {…} }
????
<prototype>: Object { … }
??? //SECOND ELEMENT
1: Object { fixture: {…}, league: {…}, teams: {…}, … }
????
fixture: Object { id: 830985, referee: "H. Prado", timezone: "UTC", … }
????
goals: Object { home: 4, away: 0 }
????
league: Object { id: 344, name: "Primera División", country: "Bolivia", … }
????
score: Object { halftime: {…}, fulltime: {…}, extratime: {…}, … }
????
teams: Object { home: {…}, away: {…} }
????
<prototype>: Object { … }
示例中僅顯示了 0 和 1,但有 305 個元素。
我遇到的問題是我無法在 for 回圈中使用 response[element].league.id 過濾那些 305(395 和 344 是上面的兩個值),因為它不起作用。
假設我有一組我想要的聯賽 ID(即 const arrWant=[395, 43, 308]),我該如何從資料中過濾掉我不想要的那些?我知道我必須使用 filter() 但不確定如何做。如果有人可以撰寫粗略的代碼或功能,那將很有幫助。API 輸出圖片
uj5u.com熱心網友回復:
使用該includes()方法測驗回應中的聯賽 ID 是否在arrWant陣列中。
使用dataType: 'json'這樣$.ajax()將決議回應中的 JSON。
const settings = {
"async": true,
"crossDomain": true,
"url": "https://v3.football.api-sports.io/fixtures?date=2021-04-07",
"method": "GET",
dataType: 'json',
"headers": {
"X-RapidAPI-Host": "v3.football.api-sports.io",
"X-RapidAPI-Key": "MY-API-KEY"
}
};
const arrWant=[395, 43, 308]
$.ajax(settings).done(function(data) {
console.log(data.response.filter(el => arrWant.includes(el.league.id)))
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/473778.html
標籤:javascript html jQuery api 休息
