Mort
Mort

Reputation: 1481

lodash filter return Cannot read property 'indexOf' of null

I need to add PipeTransform that serach for substring in array of objects property. I'm using lodash when the filter is by name it will be fine and works like a charm. but when i change name property to another, like title. its return:

Cannot read property 'indexOf' of null

my pipe code:

import * as _ from 'lodash';
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'dataFilterTitle'
})
export class DataFilterPipeByTitle implements PipeTransform {

     transform(array: any[], query: string): any {
        debugger;
        if (query) {
             return _.filter(array, row=>row.title.indexOf(query) > -1);
         }
         return array;
     }
}

error:

ERROR TypeError: Cannot read property 'indexOf' of null
at datafilterpipebyTitle.ts?071a*:12
at arrayFilter (lodash.js:603)
at Function.filter (lodash.js:9190)
at DataFilterPipeByTitle.webpackHotUpdate.../../../../../src/app/plugins/datatable/datafilterpipebyTitle.ts.DataFilterPipeByTitle.transform (datafilterpipebyTitle.ts?071a*:12)
at checkAndUpdatePureExpressionInline (core.es5.js:11350)
at checkAndUpdateNodeInline (core.es5.js:12244)
at checkAndUpdateNode (core.es5.js:12177)
at debugCheckAndUpdateNode (core.es5.js:12880)
at debugCheckDirectivesFn (core.es5.js:12821)
at Object.eval [as updateDirectives] (ListComponent.html:17)

Upvotes: 0

Views: 1993

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136174

Error clearly states that Cannot read property 'indexOf' of null, which means that title property could be null sometimes. So before doing indexOf check title exists or not.

 transform(array: any[], query: string): any {
    if (query) {
         return _.filter(array, row=> row.title && row.title.indexOf(query) > -1);
     }
     return array;
 }

Upvotes: 1

Related Questions