I have a Main.tsx file where i have a Record ,personList,with key as PersonId and value as PersonInfo,i want to delete a particular entry from personList,based on Id provided.Below is my code:
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);
};
What about use delete
keyword?
delete personList[personId];
Since you're already assigning the keys of your object to the personId
you can just do:
const Delete = (id: string): void => {
const filteredPersonList: Record<string,PersonInfo> = {}
for(let key in personList){
if(key !== id){
filteredPersonList[key] = personList[key]
}
}
setPersonList(filteredPersonList)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With