Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete an entry from a Record in typescript,based on the Id

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);
 };
like image 741
Sakshi Avatar asked Dec 23 '22 18:12

Sakshi


2 Answers

What about use delete keyword?

delete personList[personId];
like image 113
Tomáš Kubát Avatar answered Jan 13 '23 13:01

Tomáš Kubát


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)
}
like image 42
ehutchllew Avatar answered Jan 13 '23 13:01

ehutchllew