首页 > 解决方案 > 如何根据键从 Typescript 中的 Dictionary 数据结构中删除一个条目?

问题描述

我正在使用字典数据结构,其中 Key 是 Id,值是 PersonInformation,

interface PersonInformation{
FirstName:string;
SecondName:string;
Age:string;
}

如何根据 ID 从字典中删除一个人的条目。

标签: reactjstypescriptdictionary

解决方案


如果你的字典是一个,object你可以像这样删除一个对象属性:

// in case your dictionary is object:
const Dictionary = {
  firstname: 'John',
  lastname: 'Doe'
}

delete Dictionary['firstname']; // <-- Use your ID instead

console.log(Dictionary.firstname);
// expected output: undefined
// As in your comments you said your dictionary is like following:
//in case your dictionary is an Array
const Dictionary = [ ]; 
Dictionary.push({ key: PersonId , value: PersonDescription })

//in this case you can do this:

const newDictionary = Dictionary.filter(item => item.key !== id)
// newDictionary is an Array without the item with key === id

在操场上查看此链接


推荐阅读