我在TypeScript中创建了一个数组,它有一个属性,我把它用作键。如果我有那把钥匙,我怎么能从里面删除一个项目?
当前回答
和在JavaScript中一样。
delete myArray[key];
注意,这将元素设置为undefined。
最好使用Array.prototype.splice函数:
const index = myArray.indexOf(key, 0);
if (index > -1) {
myArray.splice(index, 1);
}
其他回答
let foo_object; // Itemitem(object here) to remove
this.foo_objects = this.foo_objects.filter(obj => return obj !== foo_object);
在ES6中,你可以使用以下代码:
removeDocument(doc){
this.documents.forEach( (item, index) => {
if(item === doc) this.documents.splice(index,1);
});
}
_.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
下面是一个简单的一行代码,用于按属性从对象数组中删除对象。
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);
使用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;
推荐文章
- 从元组/数组值派生联合类型
- 如何在Angular2 ngSwitch语句中使用typescript enum值
- 使用C返回一个数组
- 如何检查IEnumerable是否为空或空?
- 找到合成属性@panelState。请在您的应用程序中包含“BrowserAnimationsModule”或“NoopAnimationsModule”。
- 向对象数组添加属性
- Angular 2+和debounce
- JavaScript在数组中
- Ruby数组到字符串的转换
- 如何分割(块)一个Ruby数组成X元素的部分?
- 在TypeScript箭头函数中指定返回类型
- 如何使用jQuery与TypeScript
- 使用lodash将对象转换为数组
- 从数组中随机选择一个元素
- Angular 2模板中的标签是什么意思?