如何根据 ID 从打字稿中的记录中删除条目

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)

  • 欢迎来到堆栈溢出!我建议不要在回答中使用反问句。他们可能会被误解为根本不是答案。您正在尝试回答本页顶部的问题,不是吗?否则请删除此帖子。 (10认同)

小智 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)