Object destructuring API data so it's easier to grab?

Viewed 243
let pokeApi = ()=>{
  let randomize = Math.floor(Math.random() * 898);
  let url = `https://pokeapi.co/api/v2/pokemon/${randomize}`
  fetch(url)
    .then((res) => res.json())
    .then((pokeData) => {
      console.log(pokeData)
    })
}

I had this written before with myself manually entering pokeData to find the information. Example would be..

  pokeHeight.textContent = `Height: ${data.height} ft `;
  pokeWeight.textContent = `Weight: ${data.weight} KG `;
  1;
  pokeTemperment.textContent = `Type: ${data.types[0].type["name"]} `;
  spriteImage.src = data.sprites["front_shiny"];
  pokeName.textContent = data.name.toUpperCase();
  hp.textContent = `HP: ${data.stats[0]["base_stat"]}`;

But my programmer friend told me to try to object destructure it instead, as it's usually how he does it. I get what object destructuring technically is but I am not sure how I can set it up so it applies to the data properties.

const {height, weight, hp} = x

but how does the height in the const above = the fetch data?

1 Answers

You should apply destructing to the result of the fetch. You can do it like this:

let pokeApi = ()=>{
  let randomize = Math.floor(Math.random() * 898);
  let url = `https://pokeapi.co/api/v2/pokemon/${randomize}`
  fetch(url)
    .then((res) => res.json())
    .then(({height, weight}) => {
      console.log('Height: ', height);
      console.log('Weight: ', weight)
    })
}
Related