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?
3
Answers
As others have mentioned in the comments,
str.hasOwnProperty("types"[1])
is equivalent tostr.hasOwnProperty("y")
, which should be false. One option is to split it into two conditions:(note that the second condition could be rewritten as
str.types.length >= 1
). Ifstr
does not have atypes
property, the expression will short circuit and so the check forstr.types[1]
will never run (so won’t error).Or, you could write it more simply using optional chaining:
You don’t need the
if...else
construct here. With the operators?.
(optional chaining) and??
(nullish coalescing), you can do it in a single assignment:This works because the
name
property is assumed to be a string, and so ifstr.types[1]?.type?.name
isundefined
, we know for sure it wasn’t present, and so the??
expression will evaluate to"none"
.As an alternative, you can check the
length
oftypes
in the JSON.