Executing a filter operation on objects that contain optional variables

I'm currently working on filtering an object that includes a non-mandatory attribute. How can I handle ignoring the attribute if it doesn't exist?

  events:IEvent[];
  filteredEvents:IEvent[];

  performFilter(filterBy:string){
    filterBy = filterBy.toLocaleLowerCase();
    this.filteredEvents= this.events.filter( e =>
      e.location && e.location.city.toLocaleLowerCase().includes(filterBy))
  }

I encountered an error when using the code above

ERROR TypeError: e.location is undefined

Event Class

export interface IEvent{

    id: number,
    name: string,
    date: string,
    time: string,
    price: number,
    imageUrl: string,
    location?: {
      address: string,
      city: string,
      country: string
    },
    onlineUrl?: string,
    sessions?: ISession[]
    
}
export interface ISession{
    id: number,
    name: string,
    presenter: string,
    duration: number,
    level: string,
    abstract: string,
    voters: string[]

}

Answer №1

You have the option to manually inspect existing properties

events: IEvent[];
filteredEvents: IEvent[];

performFilter(filterBy: string) {
    filterBy = filterBy.toLocaleLowerCase();
    this.filteredEvents = this.events.filter(e => {
        if (e && e.location && e.location.city) {
          return e.location.city.toLocaleLowerCase().includes(filterBy)
        } else {
          return false;
        }
      }

    }

Alternatively, you can utilize optional chaining with ? to verify for null or undefined

Ensure that you are using TypeScript 3.7 version

performFilter(filterBy: string) {
    filterBy = filterBy.toLocaleLowerCase();
    this.filteredEvents = this.events.filter(e => {
        return e?.location?.city?.toLocaleLowerCase().includes(filterBy)
      }
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What methods can be used to check for incorrect type of a function argument in ts-jest?

I have been experimenting with a TypeScript function lately. To speed up my testing process, I decided to utilize ts-jest. However, I stumbled upon an issue that seems tricky to resolve. Despite exploring various ts-jest options, I couldn't find a so ...

Guide to acquiring a document in Angular 2

I am attempting to retrieve audio files from a server. import { Headers, Http, Response, RequestOptions, ResponseContentType } from '@angular/http'; downloadFile() { let downloadUrl = "https://firebasestorage.googleapis.com/v0/b/enoeasy-9 ...

Next JS build not displaying Typescript errors during npm build

I've been in the process of converting a Next JS project from JavaScript to TypeScript. Intentionally making mistakes to test the type checking, for example: export class Knot { position: Vector2; locked: number; deletable: boolean; isLast: bo ...

What is the process for obtaining an HTML form, running it through a Python script, and then showcasing it on the screen

I am inquiring about the functionality of html and py script. .... The user enters 3 values for trapezoidal data from the html form: height, length of side 1, and length of side 2, then clicks submit. The entered values are then sent to be calculated using ...

Encountering a Typescript issue with the updated Apollo server version within a NestJS application

After upgrading my nestJS application to use version 3.2 of apollo-server-plugin-base, I encountered two TypeScript errors related to a simple nestJS plugin: import { Plugin } from '@nestjs/graphql' import { ApolloServerPlugin, GraphQLRequest ...

Angular manages Fullcalendar, causing ViewRender to activate

I'm having trouble triggering an event when the view changes in Fullcalendar. Specifically, I need to detect when the month shifts to the previous or next one. I tried using ViewRender, but it didn't work for me. I've come across several res ...

ng serve in Angular 6 may cause compatibility issues with HttpClientModule and mat-icons

After implementing basic unit tests with Jest, I encountered an issue where my mat-icons were not displaying correctly and my HttpClient calls to the backend were returning empty responses when running the Angular app with "ng serve." Despite subscribing t ...

PAYEE_ACCOUNT_RESTRICTED: Restrictions have been placed on the merchant account

Currently working on integrating a PayPal payment gateway into an Angular website. Testing with sandbox client ID and secret ID has been successful, but upon switching to live credentials, I encountered the following error: Uncaught Error: PAYEE_ACCOUNT_RE ...

Using JavaScript and TypeScript to create a regular expression that meets three different conditions

I need assistance validating a specific element in an XML document using regular expressions. <ConfigOption>value</ConfigOption> Here are the requirements for ConfigOption: Allowed characters include letters, numbers, underscores, and spaces. ...

The NumpadTouchControl export is missing from the module

Currently, I am in the process of creating a custom directive using Angular 1.4.9 and TypeScript. The directive itself is complete, however, I am facing an issue when trying to import it into my app.ts file for registration. This is how my directive is st ...

What is the best way to retrieve the 5 most recent posts for each genre using Laravel's API

In the process of developing an application (which is my academic project), I am utilizing Laravel 5.4 as my API combined with Angular 5. The focus of my project revolves around a music blog, necessitating specific features like categories and subcategorie ...

I am curious if there is a feature in intro.js that allows for the highlighting of text or images to

I am having trouble getting intro.js to work with Ionic 4 as the highlighted text is not showing up view image here This is how I implemented the code in Angular 7: intro() { let intro = introJs.introJs(); intro.setOptions({ exitOnOverlayClick: false, ...

Declaring UMD module in TypeScript: Generating typings for a UMD module authored in TypeScript

For the purpose of learning, I created a small TypeScript library and utilized webpack to generate a JS UMD module from my TypeScript code. Here is the structure of my project: |-dist |-js |-my-lib.min.js // Minified library as UMD module | ...

What is the best way to insert a triangle shape to the bottom of a div with an opacity level set at 0.2

https://i.stack.imgur.com/sqZpM.png I've been trying to create something similar, but my triangle keeps overlapping with the background in the next section. I've already spent 3 hours on it. Any help would be greatly appreciated. Check out my c ...

Pages in Angular are being loaded multiple times when they are loaded with various parameter values

I have encountered an issue with my page setup that involves contracts and chats. Each chat corresponds to a specific contract, and depending on which chat or contract is open, the URL changes accordingly: david/contracts -> david/contracts/12 david/c ...

Using Python to locate elements in Angular with Selenium

capture Attempting to comprehend this line has proven fruitless: element = driver.find_element(By.XPATH,"//span[contains(@_ngcontent-whw-c159 data-cy,'hotel-title')]") print(element.text) Any suggestions on how to achieve this? ...

How can I access a child element within an element using Protractor?

I'm struggling to access the child element of an ng-repeat element. After searching for solutions, I came across suggestions that didn't work for me. One tip was to try something like this: var parent = element(by.repeater('')); var c ...

Having trouble with ion-item click not functioning in Ionic 3?

Working on my Ionic 3 project, I have encountered an issue with the ion-item click listener. The scenario is that I am adding text over a canvas and then attempting to change the style of the text (such as font-family, font-size, bold, and italic). The UI ...

Can wildcard paths be imported in React using Typescript?

Is there a way to dynamically import a React Typescript Component from a wildcard path, similar to the following code snippet? const Component = loadable( () => import(`../../../src/**/*/${component_name}`), ); I have searched numerous solutions on ...

What is the accurate type of control parameter in Typescript?

Recently, I developed a TypeScript React component called FormInput to use in my form. This component integrates the MUI framework and react-hook-form. However, I encountered an issue while trying to set the correct type for the "control" parameter in my c ...