Sak*_*shi 10 frontend typescript reactjs
我有一个 Main.tsx 文件,其中有一个记录,personList,键为 PersonId,值为 PersonInfo,我想根据提供的 Id 从 personList 中删除特定条目。下面是我的代码:
interface PersonInfo{
FirstName:string;
SecondName:string;
Age:string;
}
const [personList,setPersonList] = useState<Record<string,PersonInfo>>({});
//For inserting entry
const Create = () => {
setPersonList((oldList)=>{
return {
...oldList,[PersonId]:PersonDescription //PersonDescription is of type PersonInfo
}
});
};
const Delete = () => {
const newPersonList :Record<string,PersonInfo>=
personList.filter()//Here i want to delete the entry based on personId
setPersonList(newPersonList);
};
Run Code Online (Sandbox Code Playgroud)
小智 15
delete
使用关键字怎么样?
delete personList[personId];
Run Code Online (Sandbox Code Playgroud)
小智 8
由于您已经将对象的键分配给了personId
您可以执行的操作:
const Delete = (id: string): void => {
const filteredPersonList: Record<string,PersonInfo> = {}
for(let key in personList){
if(key !== id){
filteredPersonList[key] = personList[key]
}
}
setPersonList(filteredPersonList)
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
20398 次 |
最近记录: |