30 Days Of JavaScript

Day 28: PokeDex Day 3

Lesson 2: PokeDex 10

Now we have the chart displaying with placeholder data it's time to get it working with real data.

Firstly we are going to pass foundPokemon into the renderChart function. So change the line in showModal to:

1renderChart(foundPokemon);

Then modify the declaration for renderChart to receive this argument:

1const renderChart = (pokemon) => {

And then inside renderChart we need to take the stats portion of the Pokemon and convert it into an array for the data and the labels.

Right before currentChart = new Chart( ... we could simply add this line:

1const data = pokemon.stats.map((stat) => stat.base_stat);

Which uses map to grab each base_stat out of the object and create an array of just those numbers. We know that the stats will be on a set order so we can just make an array of numbers.

But ... given that we don't know for 100% certain that the stats will always be in the same order, we should do the same for the stat names as well.

So instead we will use .reduce() to make two arrays.

Add this code in instead:

1const statsData = pokemon.stats.reduce(
2  (accumulator, stat) => {
3    accumulator.names.push(stat.stat.name);
4    accumulator.values.push(stat.base_stat);
5    return accumulator;
6  },
7  { names: [], values: [] }
8);
9
10console.log(statsData);

This creates an object with two empty arrays and then for each item in pokemon.stats it adds the stat name to the names array and the stat value to the values array. If you look at the log you will see a pair of arrays in an object.

We can now set the correct array to the correct property of he chart configuration object.

Change:

1labels: ["HP", "Attack", "Defense", "Special A", "Special D", "Speed"],

To:

1labels: statsData.names,

Then:

1data: [59, 63, 80, 65, 80, 58],

To:

1data: statsData.values,

And on the line above that change:

1label: "Value",

To:

1label: pokemon.name,

Now take a look.

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co