angularangular-maps

Object Property named with ? not working inside map in Angular


I am new to Angular, the job.job_company_companyName, the job.job_company.location and the job.jobTitle, both of them work/can be searched on based on the filter: But when I added the object of Jobs with question mark (?) for example: job.job_details?.jobCountry and job.job_details?.jobCity? they are not being filtered, the 3 upper lines are being filtered except the two lines below.

What do you think I should do to make this thing work?
What to change?
Why is the property with the question mark not working properly?

here's my search.component.ts

this.filteredList$ = combineLatest(this.list$, this.filter$).pipe(
  map(([jobs, filterString]) =>jobs.filter(job => 
    job.job_company.companyName.toLowerCase().indexOf(filterString.toLowerCase()) !== -1 ||
    job.jobTitle.toLowerCase().indexOf(filterString.toLowerCase()) !== -1 ||
    job.job_company.location.toLowerCase().indexOf(filterString.toLowerCase()) !== -1 ||
    job.job_details?.jobCountry.toLowerCase().indexOf(filterString.toLowerCase()) !== -1 ||
    job.job_details?.jobCity?.toLowerCase().indexOf(filterString.toLowerCase()) !== -1 
    )),
  tap(filtered => {
    this.allJobs = filtered;
    return this.jobsChunk = filtered.slice(0, 9)
  })
);

Heres jobs.model.ts

export interface Jobs {
  jobsId: string;
  jobTitle: string;
  job_details?: JobDetails;
  job_package: JobPackage;
  job_status: JobStatus;
  job_company: CompanyProfile;
  createdDate?: string;
}

export interface JobDetails {
  jobCity?: string;
  jobCountry: string;
  jobType: string;
  jobCategory: string;
  jobTags: string[];
  jobDescription: string;
}

export interface CompanyProfile {
  companyName: string;
  location: string; 
}

Solution

  • You have an issue with the condition implementations, in that case:

    job.job_details?.jobCity?.toLowerCase().indexOf(filterString.toLowerCase()) !== -1
    

    If job_details or jobCity are undefined, the comparation will be undefined !== -1, and it will be true.

    A simple approach will be to use the > -1 instead of !== -1 condition.

    Or check the property before:

    job.job_details?.jobCity && job.job_details.jobCity.toLowerCase().indexOf(filterString.toLowerCase()) !== -1