Home > front end >  How to check if property does not exist when find in Angular
How to check if property does not exist when find in Angular

Time:07-14

I have this code:

 showInforme(){
    this.buscadorService.getInforme()
      .subscribe((data: InformesCounter) => {
          const { data: myData, included: myIncluded } = data;
          myData.forEach((item: any) => {
            const myFid = myIncluded.find((element: any) => element.attributes.drupal_internal__fid === item.relationships.informe.data.meta.drupal_internal__target_id)
              item.relationships.informe.data.meta.uri = myFid.attributes.uri;
            });
          // console.log(myData);
          this.infoFile = myData.map((data: { relationships: any;}) => data.relationships);
          // console.log(this.infoFile);
      })
  }

But when drupal_internal__target_id is not found or does not exist i receive this error in console:

ERROR TypeError: Cannot read properties of null (reading 'meta')

I need a way to skip each item who don't have this property. I don't know yet how can i do this. Thanks

CodePudding user response:

You cna do this:

 const myFid = myIncluded.find((element: any) => element.attributes.drupal_internal__fid === item.relationships.informe.data?.meta.drupal_internal__target_id)

Add ? because item.relationships.informe.data is null. In this way the error is escaped.

CodePudding user response:

You can use Optional Chaining to prevent the error.

Add the optional chaining operator ?. when you expect a null or undefined value and need to access a property. Example: item.relationships.informe.data?.meta?.drupal_internal__target_id and it will return null. Pay attention to the ?. Operator after the data and meta property.

More information about Optional Chaining can be found in the What's new in TypeScript 3.7 article.

  • Related