Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript ignore object if no data

I’m pulling the types of a Pokémon from the pokeAPI for my discord.js command. It’s working fine if a Pokémon has two types, but I’m having an issue when a Pokémon has only one type.

I define them in my file:

const type1 = types[0].type.name;
const type2 = types[1].type.name;

And load them in my embed:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
name: "Type",
value: `${type1}, ${type2}`,
inline: false,
},

The API data:

One Type

  "types": [
    {
      "slot": 1,
      "type": {
        "name": "normal",
        "url": "https://pokeapi.co/api/v2/type/1/"
      }
    }
  ],

Two Types

  "types": [
    {
      "slot": 1,
      "type": {
        "name": "poison",
        "url": "https://pokeapi.co/api/v2/type/4/"
      }
    },
    {
      "slot": 2,
      "type": {
        "name": "flying",
        "url": "https://pokeapi.co/api/v2/type/3/"
      }
    }
  ],

When I try to run my command with a Pokémon with one type, I get the following error in the console: TypeError: Cannot read properties of undefined (reading ‘type’)

I figure I’ve got to do something in the embed to ignore the second type if it isn’t there, but I can’t figure it out. I tried the following also, but the api is not returning anything, even null:

`${type1}, ${type2 == null ? `` : `${type2}`}`

Someone who can help me on the right track?

>Solution :

It seems that the second item in the array (index 1) is missing in that case. So you need to check if the array is long enough.

const type2 = types.length>1 ? types[1].type.name : null;

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading