简体   繁体   English

Object 可能是“未定义”。 在数组过滤器中

[英]Object is possibly 'undefined'. in array filter

I´m getting Object is possibly 'undefined' trying to use filter.我正在尝试使用过滤器 Object 可能是“未定义”。

interface Person {
    name: string;
    age: number;
    phone?: string;
}

let a: Person[] = [{name: "ASHLEE", age: 29},{name: "Brad", age: 32}]

const b = a.filter((item) =>
        item.phone.toLowerCase());

console.log(b);

How to solve this problem?如何解决这个问题呢? What am I doing wrong?我究竟做错了什么? Thanks!谢谢!

I am not sure what you are trying to accomplish here.我不确定您要在这里完成什么。 To filter the Persons array you can do the following, no need to lower case it.要过滤Persons数组,您可以执行以下操作,无需将其小写。

interface Person {
    name: string;
    age: number;
    phone?: string;
}

let a: Person[] = [{name: "ASHLEE", age: 29},{name: "Brad", age: 32}]

const b = a.filter((item) =>
        item.phone);

console.log(b);

If you are trying to lowercase phone you can apply a map function on the result.如果您尝试使用小写phone ,您可以在结果上应用 map function。

const b = a.filter((item) =>
        item.phone).map(item => ({...item, phone: item.phone?.toLocaleLowerCase()}))

Playground link. 游乐场链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM