Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
    })
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading