我通过检查具有唯一ID的复选框列表来向数组添加ID。如果用户再次单击复选框(取消选中),我想从数组中删除ID。如果ID已经存在,如何从数组中删除ID?
这是我编写的将ID添加到数组的功能
addEvcToArray(id) {
const stationId = {
stationId: id
}
var evcIdArray = this.state.stationIdArray.concat(stationId);
this.setState({ stationIdArray: evcIdArray })
}
在当前系统中,如果用户再次单击该复选框,则会再次添加与该复选框相关的ID。
答案 0 :(得分:1)
使用findIndex
查看具有该stationId
的索引。如果是这样,slice
数组在该索引左右两侧的两端将创建一个没有该元素的新数组:
addEvcToArray(id) {
const { stationIdArray } = this.state;
const index = stationIdArray.findIndex(({ stationId }) => stationId === id);
if (index === -1) {
this.setState({
stationIdArray: [...stationIdArray, { stationId: id }]
});
} else {
const slicedArr = [...stationIdArray.slice(0, index), ...stationIdArray.slice(index + 1)];
this.setState({
stationIdArray: slicedArr
});
}
}
或者较少重复地使用条件运算符:
addEvcToArray(id) {
const { stationIdArray } = this.state;
const index = stationIdArray.findIndex(({ stationId }) => stationId === id);
const newStationArray = index === -1
? [...stationIdArray, { stationId: id }]
: [...stationIdArray.slice(0, index), ...stationIdArray.slice(index + 1)];
this.setState({
stationIdArray: newStationArray
});
}
答案 1 :(得分:1)
您可以先检查该项目是否存在,然后添加或删除该项目。
要从数组中删除项目,可以使用filter方法。
addEvcToArray(id) {
const { stationIdArray } = this.state;
const index = stationIdArray.findIndex(({ stationId }) => stationId === id);
if (index === -1) { //not found, add
this.setState({ stationIdArray: [...stationIdArray, { stationId: id }]});
} else { //already exists, remove
const updatedArray = stationIdArray.filter(s => s.stationId !== id)
this.setState({stationIdArray: updatedArray});
}
}
答案 2 :(得分:0)
检查元素是否存在,否则请从数组中将其过滤掉,然后再次将其设置为状态:
function addEvcToArray(id) {
const stationId = {
stationId: id,
};
if (
!this.state.stationArray.find(element => element.stationId === id) // returns the object otherwise undefined
) {
const evcIdArray = this.state.stationIdArray.concat(stationId);
this.setState({ stationIdArray: evcIdArray });
} else {
this.setState({
stationIdArray: stationIdArray.filter(
element => element.stationId !== stationId, // returns an array with all values except current stationId
),
});
}
}
答案 3 :(得分:0)
尝试一下
addEvcToArray(id) {
let newArr=[]
const { stationIdArray } = this.state;
let filtered = stationIdArray.filter(filt=> filt.stationId!==id)
newArr = [...filtered , {stationId:id}];
this.setState({ stationIdArray: newArr})
}