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

时间:2021-03-10 21:28:44

标签: javascript typescript

尝试使用过滤器时,我得到的对象可能是“未定义的”。

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);

如何解决这个问题?我究竟做错了什么?谢谢!

1 个答案:

答案 0 :(得分:0)

我不确定您要在这里完成什么。要过滤 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);

如果您尝试小写 phone,您可以对结果应用映射函数。

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

Playground link.