0

I am trying to get data from an API but am having trouble. The layout of the data is as follows:

{
  "stats": [{
    "base_stat": 45,
    "effort": 0,
    "stat": {
      "name": "hp",
      "url": "https://pokeapi.co/api/v2/stat/1/"
    }
  }]
}

I want to get the "base_stat" number to appear after the "stat" name so I will simply look like this: "Hp: 45" (I want it capitalized also)

The other problem I have is that the title runs through the entire list of names, I want it to be the same name the first modal had.

Here is my code and here is my codepen as this project is too big to put it all here.

Codepen: https://codepen.io/drxl/pen/WNjJQXa

API: https://pokeapi.co/api/v2/pokemon/?limit=150 (original)

https://pokeapi.co/api/v2/pokemon/1/(where the stats are)

What I have tried:

   function loadStats(item) {
      let url = item.detailsUrl;
      return fetch(url).then(function (response) {
         return response.json();
      }).then(function (details) {
         //add details to stats
         item.stats = [];
         for (var i = 0; i < details.stats.length; i++) {
            item.stats.push(details.stats[i].stat.name);
         }
         item.stats = item.stats.join(': <br>');
         
         item.stats = [];
         for (var a = 0; a < details.stats.base_stath; a++) {
            item.stats.base_stat.push(details.stats[a].base_stat);
         }

      }).catch(function (e) {
         console.error(e);
      });
   }

1 Answer 1

1

You can get the data structure you want by mapping the initial data

item.stats = details.stats.map(({ base_stat, stat: { name } }) =>
  `${name}: ${base_stat}`).join("<br/>")
Sign up to request clarification or add additional context in comments.

7 Comments

Ok so it is close but it says "undefined at the very end and it still runs through all the names. I want it to be the name of the pokemon that I clicked on
Nothing to do with the code in my answer. You get undefined because you have $("<p>" + item.stats + item.base_stat + "<p>"); and item.base_stat isn't defined
Right, I forgot about that. I got rid of it. Do you know how to stop it from running through everything? It needs to show the name that I clicked on.
You're adding the click handler for loading each item to the same button ID (#base-stats-button) so when you click it, it runs them all. Keep in mind, every time you call addEventListener() on the same element, the event listeners just stack up; they are not replaced or overwritten
Honestly, I am a noob and I don't know how to fix it
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.