我的Angular应用程序中有以下界面:
interface Reservation {
id: string;
from: Date;
to: Date;
}
interface Bedroom {
id: string;
reservations: Array < Reservation > ;
}
interface House {
id: string;
bedrooms: Array < Bedroom >;
}
在某些时候,我必须从Reservation
Bedroom
内的某个Array
内删除House
并返回整个House
的副本1}} Array
仅在没有删除Reservation
项的情况下。
我无法改变Array
的现有House
。我该怎么做?
答案 0 :(得分:0)
你应该在你的数组上使用splice
方法,使用对象克隆的组合(即由underscore.js提供):
https://www.w3schools.com/jsref/jsref_splice.asp
http://underscorejs.org/#clone
这将是 (我没有检查代码):
import * as _ from 'underscore';
removeReservation(bedroom: Bedroom, reservation: Reservation): Bedroom {
let position = bedroom.reservations.findIndex(checkingRes => {
return checkingRes.id == reservation.id
});
let bedroomCopy = _.clone(bedroom);
bedroomCopy.reservations.splice(position, position + 1);
return bedroomCopy;
}
如果您想要逐个删除预订,只需省略克隆操作。
removeReservation(bedroom: Bedroom, reservation: Reservation): Bedroom {
let position = bedroom.reservations.findIndex(checkingRes => {
return checkingRes.id == reservation.id
});
bedroom.reservations.splice(position, position + 1);
return bedroom;
}