我在TypeScript中创建了一个数组,它有一个属性,我把它用作键。如果我有那把钥匙,我怎么能从里面删除一个项目?
当前回答
_.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
其他回答
和在JavaScript中一样。
delete myArray[key];
注意,这将元素设置为undefined。
最好使用Array.prototype.splice函数:
const index = myArray.indexOf(key, 0);
if (index > -1) {
myArray.splice(index, 1);
}
只是想为数组添加扩展方法。
interface Array<T> {
remove(element: T): Array<T>;
}
Array.prototype.remove = function (element) {
const index = this.indexOf(element, 0);
if (index > -1) {
return this.splice(index, 1);
}
return this;
};
您可以尝试先获取列表或数组的索引或位置,然后使用for循环将当前数组分配给临时列表,过滤掉不想要的项并将想要的项存储回原始数组
removeItem(index) {
var tempList = this.uploadFile;
this.uploadFile = [];
for (var j = 0; j < tempList.length; j++) {
if (j != index)
this.uploadFile.push(tempList[j]);
}
}
如果你需要从数组中删除一个给定的对象,并且你想确定以下情况,请使用此方法:
列表没有重新初始化 正确更新数组长度
const objWithIdToRemove;
const objIndex = this.objectsArray.findIndex(obj => obj.id === objWithIdToRemove);
if (objIndex > -1) {
this.objectsArray.splice(objIndex, 1);
}
这对我很管用。
你的数组:
DummyArray: any = [
{ "id": 1, "name": 'A' },
{ "id": 2, "name": 'B' },
{ "id": 3, "name": 'C' },
{ "id": 4, "name": 'D' }
]
功能:
remove() {
this.DummyArray = this.DummyArray.filter(item => item !== item);
}
注意:这个函数删除数组中的所有对象。如果你想从数组中删除一个特定的对象,那么使用这个方法:
remove(id) {
this.DummyArray = this.DummyArray.filter(item => item.id !== id);
}
推荐文章
- 如何读一个文本文件到一个列表或数组与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()返回更具体的类型
- 如何从对象数组中通过对象属性找到条目?
- 如何从关联数组中删除键及其值?