I’m still pretty new to programming and I’m building a random Pokemon generator in JavaScript using a Pokemon API, I’m having trouble making the Pokemon type show up in a fetch request because it is nestled in an array in the API.
I can fetch the name
, id
, and base experience
values just fine, because they are listed as their own individual values within the API, but types show up as [object Object]
because they are listed in an array and I’m not quite sure how to retrieve them. Here is my code and a link the the API I’m using
const name = document.getElementById('name')
const id = document.getElementById('id')
const type = document.getElementById('type')
const baseexperience = document.getElementById('baseexperience')
const button = document.querySelector('.myButton');
button.addEventListener('click', (e) => {
e.preventDefault()
const randomPokemon = Math.ceil(Math.random() * 1017)
fetch(`https://pokeapi.co/api/v2/pokemon/${randomPokemon}`)
.then(response => response.json())
.then(pokemon => {
console.log(pokemon)
name.innerHTML = pokemon['name']
id.innerHTML = pokemon['id']
type.innerHTML = pokemon['types']
baseexperience.innerHTML = pokemon['base_experience']
})
})
<body>
<div id="name"></div>
<div id="id"></div>
<div id="type"></div>
<div id="baseexperience"></div>
<button class="myButton">Catch 'em all</button>
</body>
2
Answers
The
types
property is an array of objects, for example:JavaScript has no default way of representing this data as a string, other than something like
[object Object],[object Object]
. You’d need to indicate what you want to display.For example, if you want to display the type names as a comma-separated list, you can
.map()
over that array to project it to a list of strings, and then.join()
those strings by a comma. Something like this:Edit: It appears that it can display at least an array of strings, and would insert a comma automatically:
Though you could still use
.join()
to include a space after the comma for readability of course. You could also modify the logic to display them as<li>
elements in a<ul>
, etc.Try this instead:
You was trying to print two objects. With Totaltypes you save every type’s name in a string and the string value.