I'm currently building a Pokémon application, therefor I'm accessing data from PokéAPI and will store specific data in a variable, such as name, id and type.
Currently I'm facing issues to store the second type of a pokémon. Some of them have one type, some of them have two.
If a pokémon has two types the data structure looks like this: Bulbasaur JSON data screenshot from pokeapi.co/api/v2/pokemon/bulbasaur
Here's the link to JSON data for an example pokémon with 1 types: https://pokeapi.co/api/v2/pokemon/bulbasaur
If a pokémon only has one type the structure looks like this: Togepi JSON data screenshot from https://pokeapi.co/api/v2/pokemon/togepi
Link: https://pokeapi.co/api/v2/pokemon/togepi
To check whether there's a second type or not I wrote a function:
function CheckPropertySecondtype(str) {
if (str.hasOwnProperty("types"[1])) {
pokemondata.secondtype = str.types[1].type.name;
console.log("Pokemon has a second type");
} else {
pokemondata.secondtype = "none";
console.log(str.types[1].type.name);
}
}
The problem is, that the if statement doesn't work the way I want it to. It's always false which means no matter if there's a second type or not, the output is always "none". I tried several notations like hasOwnProperty(types[1].type.name) or hasOwnProperty(types1.type.name).
How can I access the key correctly to check this?
"types"[1]is the string"y", sostr.hasOwnProperty("types"[1])is equivalent tostr.hasOwnProperty("y")str?.types?.[1]str.types[1].type.nameI shouldn't need optional chaining, right? I just don't know how to writestr.types[1].type.nameas prop in.hasOwnProperty()whenstr.hasOwnProperty(types[1].type.name)is impossible