lodash 过滤器 return 无法读取 属性 'indexOf' 的 null
lodash filter return Cannot read property 'indexOf' of null
我需要添加 PipeTransform 以搜索对象数组 属性 中的子字符串。当过滤器按 name 时,我正在使用 lodash,它会很好并且像一个魅力一样工作。但是当我将名称 属性 更改为另一个名称时,例如 title。它的 return:
Cannot read property 'indexOf' of null
我的管道代码:
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 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)
错误明确指出 无法读取 null 的 属性 'indexOf',这意味着 title
属性 可能是 null
有时。所以在做 indexOf
之前检查 title
是否存在。
transform(array: any[], query: string): any {
if (query) {
return _.filter(array, row=> row.title && row.title.indexOf(query) > -1);
}
return array;
}
我需要添加 PipeTransform 以搜索对象数组 属性 中的子字符串。当过滤器按 name 时,我正在使用 lodash,它会很好并且像一个魅力一样工作。但是当我将名称 属性 更改为另一个名称时,例如 title。它的 return:
Cannot read property 'indexOf' of null
我的管道代码:
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 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)
错误明确指出 无法读取 null 的 属性 'indexOf',这意味着 title
属性 可能是 null
有时。所以在做 indexOf
之前检查 title
是否存在。
transform(array: any[], query: string): any {
if (query) {
return _.filter(array, row=> row.title && row.title.indexOf(query) > -1);
}
return array;
}