选择过滤后的可选对象数组

Selecting a filtered array of optional objects

我是 Angular 的新手,我很难弄明白这一点。我有一个部件 ID,我正在尝试 select 所有具有相同部件 ID 的(可选)公司对象。

export class Part {
    id: number;
    name: string;
    company?: Company[];
}

...

public parts: Part[];
public filteredCompanies: Company[];

...

public filterCompanies(): void {
    this.filteredCompanies = this.parts.filter(part => part.id === retrievedID).map(part => part.company);
}

以下行给我一个错误,在 this.filteredCompanies 下有一条红色波浪线:

Type 'Company[][]' is not assignable to type 'Company[]'. Type 'Company[]' is missing the following properties from type 'Company': id, name, description, ...

我认为语法是正确的,但我确实遗漏了什么。

您的代码 returns 一个 Company[] 数组,每个数组都来自过滤后的 Part。您可以通过调用 flat 方法将 Company[][] 转换为 Company[]

this.filteredCompanies = this.parts.filter(...).map(part => part.company || []).flat();

由于 flat 在 Internet Explorer 中不可用,如果您需要支持该浏览器,可以使用 MDN documentation 中建议的备选方案之一。这是一种可能的选择:

this.filteredCompanies = this.parts.filter(...).map(part => part.company || [])
                                   .reduce((acc, val) => acc.concat(val), [])

有关演示,请参阅 this stackblitz