Home > Enterprise >  Javascript ignore object if no data
Javascript ignore object if no data

Time:08-13

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:

{
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?

CodePudding user response:

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;

CodePudding user response:

At its core, the issue is that the array can be any length. I think a better approach here would be something like this:

var typeList = types.map(t => t.name).join(', ');

This will produce the comma-separated listing without concerning yourself with its length.

Then you can build the object like this:

{
  name: "Type",
  value: typeList,
  inline: false,
}

CodePudding user response:

If you're using ES6, you could use nullish coalescing operator to shorten up your code.

Eg:

const type2 = type[1]?.type?.name ?? null;

  • Related