我在TypeScript中创建了一个数组,它有一个属性,我把它用作键。如果我有那把钥匙,我怎么能从里面删除一个项目?
当前回答
这对我很管用。
你的数组:
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);
}
其他回答
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));
还有一个使用Typescript的解决方案:
let updatedArray = [];
for (let el of this.oldArray) {
if (el !== elementToRemove) {
updated.push(el);
}
}
this.oldArray = updated;
我们可以使用筛选器和包含来实现逻辑
const checkAlpha2Code = ['BD', 'NZ', 'IN'] let countryAlpha2Code = ['US', 'CA', 'BD', 'NZ', 'AF' , 'AR' , 'BR'] /** * Returns the modified array countryAlpha2Code * after removing elements which matches with the checkAlpha2Code */ countryAlpha2Code = countryAlpha2Code.filter(alpha2code => { return !checkAlpha2Code.includes(alpha2code); }); console.log(countryAlpha2Code) // Output: [ 'US', 'CA', 'AF', 'AR', 'BR' ] // Resetting the values again countryAlpha2Code = ['US', 'CA', 'BD', 'NZ', 'AF' , 'AR' , 'BR'] /** * Returns the modified array countryAlpha2Code * which only matches elements with the checkAlpha2Code */ countryAlpha2Code = countryAlpha2Code.filter(alpha2code => { return checkAlpha2Code.includes(alpha2code); }); console.log(countryAlpha2Code) // Output: [ 'BD', 'NZ' ]
类似于Abdus Salam Azad的答案,但将数组作为参数 / / https://love2dev.com/blog/javascript-remove-from-array/
function arrayRemove(arr:[], value:any) {
return arr.filter(function(ele){
return ele != value;
});
}
使用TypeScript扩展运算符(…)
// Your key
const key = 'two';
// Your array
const arr = [
'one',
'two',
'three'
];
// Get either the index or -1
const index = arr.indexOf(key); // returns 0
// Despite a real index, or -1, use spread operator and Array.prototype.slice()
const newArray = (index > -1) ? [
...arr.slice(0, index),
...arr.slice(index + 1)
] : arr;
推荐文章
- 如何读一个文本文件到一个列表或数组与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()返回更具体的类型
- 如何从对象数组中通过对象属性找到条目?
- 如何从关联数组中删除键及其值?