我在 Ionic/Angular 中有以下接口(interface)(为了清晰起见,省略了细节),这就是我使用 Typescript/ES6 的原因:
export interface Item {
statusOfItem: string;
}
export interface checkin {
items: Array<Item>;
}
export interface table {
checkins: Array<Checkin>;
}
我需要编写一个传入表对象的函数,但表中的 checkin 均按其状态进行过滤。
这是我想出的函数:
transformTable(table: Table, status: string): Table{
let newTable: Table = table;
newTable.checkins = table.checkins.map(
checkin => {
let newCheckin: Checkin = checkin;
newCheckin.items = checkin.items.filter(
item => item.statusOfItem == status
);
return newCheckin;
}
)
return newTable;
}
我喜欢使用新的数组函数,如map等。这可以更有效地完成/编写(例如,没有let
)。
最佳答案
我相信您不需要将函数的参数重新实例化为新的 let
变量。只需按原样使用它们即可。
transformTable(table: Table, status: string): Table{
table.checkins = table.checkins.map(checkin => {
checkin.items = checkin.items.filter( item => item.statusOfItem == status )
return checkin
})
return table
}
这也应该有效。不管怎样,我一直这样做,而且很有效:)
关于javascript - ES6/ typescript : Stacking map and filter advanced array methods,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48808800/