Search code examples
javascriptjavascript-objects

Using hasOwnProperty for nested object keys if key name is a number


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?


Solution

  • 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:

    pokemondata.secondtype = str.types[1]?.type?.name ?? "none";
    

    This works because the name property is assumed to be a string, and so if str.types[1]?.type?.name is undefined, we know for sure it wasn't present, and so the ?? expression will evaluate to "none".