我在TypeScript中自定义了数组。
array = [{ name: "Hardik", city: null, job: null },
{ name: "John", city: "Ahmedabad", job: "IT" },
{ name: "Margie", city: "Mumbai", job: "CA" },
{ name: "Creature", city: "Banglore", job: null },
{ name: "Smooth", city: null, job: null }];
我想根据城市和工作来过滤此数组。另外,我需要检查不区分大小写。所以我转换为ToLowerCase。
this.filter = this.array.filter(i =>
i.job.toLowerCase().indexOf('ca') != -1 ||
i.city.toLowerCase().indexOf('ahmedabad') != -1
)
如果列不为空,则哪个可以正常工作。如果该列为null,则给出错误,不能为null的LowerCase()。所以,我首先检查列是否为空。
this.filter = this.array.filter(i =>
i["job"] != null ? i.job.toLowerCase().indexOf('ca') != -1 : false ||
i["city"] != null ? i.city.toLowerCase().indexOf('ahmedabad') != -1 : false
)
但是输出错误。
[ { "name": "Margie", "city": "Mumbai", "job": "CA" } ]
预期输出为:
[{ name: "John", city: "Ahmedabad", job: "IT" },
{ name: "Margie", city: "Mumbai", job: "CA" }]
链接:https://stackblitz.com/edit/filter-with-tolowercase-and-null?file=src/app/app.component.ts
答案 0 :(得分:1)
我可以通过如下更改代码来获得正确答案:
this.filter = this.array.filter(i =>
(i["job"] && i.job.toLowerCase().indexOf('ca') != -1) ||
(i["city"] && i.city.toLowerCase().indexOf('ahmedabad') != -1)
)
答案 1 :(得分:0)
this.filter = this.array.filter(i =>
(i["job"] != null ? i.job.toLowerCase().indexOf('ca') != -1 : false) ||
(i["city"] != null ? i.city.toLowerCase().indexOf('ahmedabad') != -1 : false)
)
问题是由于运营商优先