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 输出图片
使用该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)))
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句