NucyLoodle
NucyLoodle

Reputation: 85

Accessing PokeAPI

I would like to access the PokeAPI to get all the moves learnt by a specific pokemon at level 1. At the moment,

Here is my js code:

let userPokemonName = "squirtle"
const pokeData = [];
const url = `https://pokeapi.co/api/v2/pokemon/${userPokemonName}`
pokeData.push(fetch(url).then(res => res.json()))

Promise.all(pokeData).then(results => {
  console.log(results)
  const userPokemonData = results.map(data => ({
    name: data.name,
    id: data.id,
    type: data.types.map(type => type.type.name).join(", "),
    moves: data.moves.map(move => {
      if (move.version_group_details.level_learned_at === 1) {
        return move.move.name
      }
    }).slice(0, 10).join(', ')
  }));
})

At the moment, I'm just getting an array of commas moves array is commas

but it should say ['tackle', 'tail-whip'].

I have tried using .forEach instead of map :

 moves: data.moves.forEach(move => {
      if (move.version_group_details.level_learned_at === 1) {
        userPokemonData.push(move.move.name)
      }

but this has returned undefined.

Upvotes: 0

Views: 89

Answers (1)

mplungjan
mplungjan

Reputation: 178375

You can use reduce like this

let userPokemonName = "squirtle"
const url = `https://pokeapi.co/api/v2/pokemon/${userPokemonName}`
fetch(url)
  .then(res => res.json())
  .then(userPokemonData => {
    //console.log(userPokemonData)
    const { name, id, types, moves } = userPokemonData;
    console.log(name, id, types);
    const movesDetails = moves
      .reduce((acc,move) => {
        if (move?.version_group_details
                ?.some(detail => detail.level_learned_at===1)) {
          acc.push(move.move.name);
        }
        return acc;
      },[])
        
      
    console.log(movesDetails);
      //).slice(0, 10).join(', ')

    });
  

Upvotes: 1

Related Questions