Estoy estudiando Javascript. Y para eso estoy haciendo un Juego Pokémon basado en la PokéAPI
Para hacerlo simple, quiero recuperar - filtrar - Pokémons con tipos Fuego, Agua y Hierba.
Entiendo que debo ir a datos> tipos> (buscar en las ranuras 1 y 2)> buscar hierba, fuego y agua.
Este es mi código, hasta ahora, y estaba pensando si podría hacerlo ANTES de recuperar los datos en la API. De lo contrario, tendré que recuperar CADA Pokémon y luego filtrarlos.
const baseUrl = 'https://pokeapi.co/api/v2/pokemon/?limit=150' try { fetch(baseUrl) .then(response => { const responseJson = response.json() return responseJson }) .then(async data => { const pokemons = data.results for (const pokemon of pokemons) { pokemon.data = await fetch(pokemon.url).then(res => res.json()) } console.log(pokemons) }) .catch(error => { console.error(error) }) } catch (error) { console.error(error) }Si no normaliza los datos de la API, debe filtrar utilizando esta lista. Pero cuando obtienes la lista de Pokémon, puedes normalizar la lista a una estructura más amigable para tu aplicación.
function normalizeList (item = {}) { const { name, data } = item // Define your normalized data here return { name, types: data.types } }Si necesita transformar/analizar o lo que sea, le recomiendo que cree un PokemonModel y cree instancias de Pokemon Class:
class PokemonModel { constructor(data = {}) { this.name = data.name this.types = this._getTypes(data.types) } _getTypes(types = []) { return types.map((type) => { return { name: type.name } }) } }Su código con PokemonModel:
class PokemonModel { constructor(data = {}) { this.name = data.name this.types = this._getTypes(data.types) } _getTypes(types = []) { return types.map((type) => { return { name: type.name } }) } } const baseUrl = 'https://pokeapi.co/api/v2/pokemon/?limit=150' const pokemonList = [] try { fetch(baseUrl) .then(response => { const responseJson = response.json() return responseJson }) .then(async data => { const pokemons = data.results for (const pokemon of pokemons) { pokemon.data = await fetch(pokemon.url).then(res => res.json()) pokemonList.push(new PokemonModel(pokemon.data)) } console.log(pokemonList) }) .catch(error => { console.error(error) }) } catch (error) { console.error(error) }