[Fixed] Performing filter on Objects with non-mandatory variables

Issue

I am trying to perform a filter on an object that has an attribute that is non mandatory. I am trying to ignore the attribute if it does not exist. How to do I do that?

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

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

I got an error of using above code

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[]

}

Solution

You can either manually check properties existing

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;
        }
      }

    }

Or use optional chaining. ? only checks for null or undefined

Make sure you have TypeScript 3.7 version

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

Leave a Reply

(*) Required, Your email will not be published