Home > database >  How can I use the filter() function to filter this set of data from API?
How can I use the filter() function to filter this set of data from API?

Time:05-14

API Call code:

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

the format of the API data is:

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 { … }

only 0 and 1 are shown in the example but there are 305 elements.

The issue I am having is that I cannot filter those 305 in a for loop with by response[element].league.id (395 and 344 are two values above) because it wont work.

assuming I have an array of league ID's I want (ie. const arrWant=[395, 43, 308]), how do I go about filtering out the ones I don't want from the data? I am aware I must use filter() but am unsure how to do it. if someone could write a rough code or function it would be helpful.Picture of API Output

CodePudding user response:

Use the includes() method to test if the league ID in the response is in the arrWant array.

Use dataType: 'json' so that $.ajax() will parse the JSON in the response.

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)))

});

  • Related