[英]ES6 / Typescript: Stacking map and filter advanced array methods
我在 Ionic / Angular 中有以下接口(為了清楚起見減去細節),這就是我使用 Typescript / ES6 的原因:
export interface Item {
statusOfItem: string;
}
export interface checkin {
items: Array<Item>;
}
export interface table {
checkins: Array<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
}
這也應該有效。 無論如何,我一直這樣做並且它有效:)
對於任何感興趣的人,感謝Bergi和Jeremy我最終得到了這個代碼:
private copyTableByStatus(table: Table, status: string): Table{
// XXX: Weird, javascript can't deep copy. Object.assign() only creates
// shallow copies. There should be something like Object.clone() ...
let newTable: Table = JSON.parse(JSON.stringify(table));
newTable.checkins = JSON.parse(JSON.stringify(table.checkins.map(
checkin => {
checkin.items = JSON.parse(JSON.stringify(checkin.items.filter(
item => item.statusOItem == status
)))
return checkin;
}
)))
return newTable;
}
謝謝你們倆。 我不知道,javascript 不能復制對象! :( 太傷心了...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.