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((data) => {
console.log(data)
let {height, weight, stats:{0: {base_stat}} } = data;
})
}
pokeApi();
stats is defined as an array with 6 objects. I'm trying to call line 0, and inside of 0 the name, but whenever I type a number it gives me an error I can't fix unless I delete the number.
How can I destructure so it equals this... data.stats[0]["base_stat"]
To get the first element of array with the help of destructure, you can do like,
stats:[ {base_stat: firstBaseStat} ]
So the final destructuring will be like,
let {height, weight, stats:[ {base_stat: firstBaseStat} ] } = data;
And you can make use of firstBaseStat to get the first value.
Working Example:
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((data) => {
let {height, weight, stats:[ {base_stat: firstBaseStat} ] } = data;
console.log('height ', height, 'weight ', weight, 'first stats ', firstBaseStat)
})
}
pokeApi();