javascriptreactjsarraysobjectfilter

filter out object in array if object key value is null


I need to filter out objects in array if specific key value is null.(trying to learn)

const getPlayerData = async () => {
  const allPlayers = await fetchData("https://api.sleeper.app/v1/players/nfl");
  const players = Object.keys(allPlayers).map(function(key) {
    return allPlayers[key]
  })

  const activePlayers = await Promise.all(players?.filter(async(player: any) => {player.search_rank !== null}
).sort((a, b) => a.search_rank - b.search_rank));
  
  console.log(activePlayers)
  return activePlayers;
}

it filters if {player.active = true} but i need to filter if player.search_rank is null aswell


Solution

  • I've modified the above code assuming that fetchData function will get the data from API. Please ignore the implementation of fetchData.

    const fetchData = async (url) => {
        return await fetch(url).then(res => res.json())
    }
    
    const getPlayerData = async () => {
      const allPlayers = await fetchData("https://api.sleeper.app/v1/players/nfl");
      const players = Object.keys(allPlayers).map((key) => allPlayers[key]);
    
      const activePlayers = players
              ?.filter((player) => player.search_rank !== null) 
              .sort((a, b) => a.search_rank - b.search_rank);
      
      console.log(activePlayers)
      return activePlayers;
    }

    Changes made:

    The main issue is we have to return player.search_rank !== null which is present inside filter function or write it as arrow function without brackets {}.