我在TypeScript中创建了一个数组,它有一个属性,我把它用作键。如果我有那把钥匙,我怎么能从里面删除一个项目?
当前回答
这是我的解决方案:
onDelete(id: number) {
this.service.delete(id).then(() => {
let index = this.documents.findIndex(d => d.id === id); //find index in your array
this.documents.splice(index, 1);//remove element from array
});
event.stopPropagation();
}
其他回答
Let departments是一个数组。您要从此数组中删除一项。
departments: string[] = [];
removeDepartment(name: string): void {
this.departments = this.departments.filter(item => item != name);
}
和在JavaScript中一样。
delete myArray[key];
注意,这将元素设置为undefined。
最好使用Array.prototype.splice函数:
const index = myArray.indexOf(key, 0);
if (index > -1) {
myArray.splice(index, 1);
}
还有一个使用Typescript的解决方案:
let updatedArray = [];
for (let el of this.oldArray) {
if (el !== elementToRemove) {
updated.push(el);
}
}
this.oldArray = updated;
Typescript/Javascript中的多个选项可以从数组中删除一个元素。 拼接是最好的选择
它在不创建新对象的情况下删除内联 它正确地更新数组的长度(不会留下空白的null元素)
下面是一个使用Splice函数根据对象数组中的某个字段删除对象的示例
Const persons = [ { 名字:“约翰”, 姓:“米歇尔” }, { 名字:“威廉”, 姓:“斯科特。” }, { 名字:“阿曼达”, 姓:“裁缝” } ] console.log('删除前:'+JSON.stringify(persons)); console.log(“删除威廉:”); persons.splice(人。findIndex(item => item。firstName === 'William'),1); console.log('After Deleting William'+JSON.stringify(persons));
let foo_object; // Itemitem(object here) to remove
this.foo_objects = this.foo_objects.filter(obj => return obj !== foo_object);
推荐文章
- 比较JUnit断言中的数组,简洁的内置方式?
- 数组到哈希Ruby
- 将Set<T>转换为List<T>的最简洁的方法
- TypeScript错误:属性“X”在类型“Window”上不存在
- Java 8流和数组操作
- 在javascript中从平面数组构建树数组
- 从另一个列表id中排序一个列表
- 我怎么能计算在打字稿2日期之间的时间
- 在bash中传递数组作为参数
- 正确使用错误
- 如何在c++中初始化一个向量
- 用any可以吗?'来检查数组是否为空?
- 从IEnumerable<KeyValuePair<>>重新创建字典
- 为什么我们使用数组而不是其他数据结构?
- 如何修复TS2322:“可以实例化与约束'对象'的不同子类型”?