【问题标题】:lodash filter return Cannot read property 'indexOf' of nulllodash过滤器返回无法读取null的属性'indexOf'
【发布时间】:2017-08-12 07:09:48
【问题描述】:

我需要在对象属性数组中添加 PipeTransform 来搜索子字符串。当过滤器是 name 时,我正在使用 lodash,它会很好并且像魅力一样工作。但是当我将名称属性更改为另一个时,例如 title。它的回报:

无法读取 null 的属性“indexOf”

我的管道代码:

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)

【问题讨论】:

  • 你能发布你的数组对象吗?

标签: javascript angular typescript underscore.js lodash


【解决方案1】:

错误明确指出 无法读取 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;
 }

【讨论】:

  • 哇,谢谢。这是我的错!
猜你喜欢
  • 1970-01-01
  • 2016-05-22
  • 2019-02-02
  • 2017-07-15
  • 1970-01-01
  • 2017-06-09
  • 2020-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多