我在TypeScript中创建了一个数组,它有一个属性,我把它用作键。如果我有那把钥匙,我怎么能从里面删除一个项目?
当前回答
let foo_object; // Itemitem(object here) to remove
this.foo_objects = this.foo_objects.filter(obj => return obj !== foo_object);
其他回答
下面是一个简单的一行代码,用于按属性从对象数组中删除对象。
delete this.items[this.items.findIndex(item => item.item_id == item_id)];
or
this.items = this.items.filter(item => item.item_id !== item.item_id);
这是我的解决方案:
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 a: number[] = [];
a.push(1);
a.push(2);
a.push(3);
let index: number = a.findIndex(a => a === 1);
if (index != -1) {
a.splice(index, 1);
}
console.log(a);
_.pull(array,'a');
使用lib lodash https://lodash.com/docs/4.17.15#pull complelte代码:
import _ from 'lodash';
const allTagList = ['a','b','b']
_.pull(allTagList, b);
console.log(allTagList) // result: ['a']
PS: Lodash提供了大量的操作符,建议使用它来简化您的代码。https://lodash.com
在ES6中,你可以使用以下代码:
removeDocument(doc){
this.documents.forEach( (item, index) => {
if(item === doc) this.documents.splice(index,1);
});
}
推荐文章
- 如何读一个文本文件到一个列表或数组与Python
- 如何在Python中将十六进制字符串转换为字节?
- 获取函数的返回类型
- 为什么是事件。目标不是元素在Typescript?
- 与push()相反;
- 如何生成。d。ts“typings”定义文件从现有的JavaScript库?
- 用“+”(数组联合运算符)合并两个数组如何工作?
- 在定义文件(*d.ts)中导入类
- 如何在Angular 2.0中使用/创建动态模板来编译动态组件?
- 在typescript中一直使用。tsx而不是。ts有什么缺点吗?
- 如何使用this.router.parent.navigate('/about')导航到另一个路由?
- 在Java中保存最后N个元素的大小有限的队列
- 使arrayList.toArray()返回更具体的类型
- 如何从对象数组中通过对象属性找到条目?
- 如何从关联数组中删除键及其值?