Javascript 如何从两个阵列中删除数据?
我有一个网格,不时显示时间列表 比如说Javascript 如何从两个阵列中删除数据?,javascript,reactjs,kendo-grid,Javascript,Reactjs,Kendo Grid,我有一个网格,不时显示时间列表 比如说 timeList=[{from:12:00:00 , to:14:00:00 ,id:10}{from:08:00:00 , to:09:00:00 ,id:11{from:05:00:00 , to:10:00:00 ,id:12}}] time=[{Value:12:00:00 id:10} {Value:14:00:00 id:100} {Value:08:00:00 id:11} {Value:09:00:00
timeList=[{from:12:00:00 , to:14:00:00 ,id:10}{from:08:00:00 , to:09:00:00 ,id:11{from:05:00:00 , to:10:00:00 ,id:12}}]
time=[{Value:12:00:00 id:10}
{Value:14:00:00 id:100}
{Value:08:00:00 id:11}
{Value:09:00:00 id:110}
{Value:05:00:00 id:12}
{Value:10:00:00 id:15}
]
要删除项目,我有以下代码
deleteTimeView(data) {
////date ==>{from:12:00:00 , to:14:00:00 ,id:10}
let indexOfDeleted = -1;
let time = this.state.time;
let timeList=this.state.timeList;
this.state.time.forEach((item, index) => {
if (item.Id === data.id) {
indexOfDeleted = index;
}
})
time.splice(indexOfDeleted, 1);
time.splice(indexOfDeleted, 1);
timeList.splice(indexOfDeleted, 1);
this.setState({
time: time,
timeList: timeList
});
}
我的问题是,当我想删除id12时,我有索引4,但我在timeList中没有这个索引。
我可以及时删除该项,但如何将其从时间列表中删除呢?首先,不要使用.splice,它会使数组发生变异,在这种情况下,表示您正在直接变异状态。永远不要改变反应中的状态
其次,基于ID的简单过滤方法应满足您的需求:
deleteTimeView(data) {
this.setState({
time: this.state.time.filter(t => t.id !== data.id),
timeList: this.state.timeList.filter(t => t.id !== data.id)
});
}
首先,不要使用.splice,它会变异数组,在本例中,这意味着您正在直接变异状态。永远不要改变反应中的状态
其次,基于ID的简单过滤方法应满足您的需求:
deleteTimeView(data) {
this.setState({
time: this.state.time.filter(t => t.id !== data.id),
timeList: this.state.timeList.filter(t => t.id !== data.id)
});
}