我的数组结构如下:
[
{key: 4, data: {…}, qText: {…}},
{key: 4, data: {…}, qText: {…}, isVisible: false},
{key: 5, data: {…}, qText: {…}, isVisible: false},
{key: 4, data: {…}, qText: {…}, isVisible: false}
]
我想根据两个条件从中删除元素:
key
应该匹配,所以如果我要删除key:4
,那应该是一个条件。2
,那么只应该删除第三个key:4
。我的方法包含很多循环,并且无效。最佳方法性能明智的做法是什么? 1)试图找到以下密钥
const deleteKey = this.followUpQues.filter(quest =>
quest.data.choice.some(y => y.id === item.id)
).map(quest =>
quest.key
)
2)试图找到以下索引
this.followUpQues.forEach(function(val, index) {
if (val.data.choice.filter(y => y.id === item.id).length >= 1) {
keyNumber = val.key;
valueIndex = index;
}
})
this.followUpQues.splice(valueIndex + 1, this.followUpQues.length - (valueIndex + 1))
答案 0 :(得分:1)
const values = [
{key: 4, data: {}, qText: {}},
{key: 4, data: {}, qText: {}, isVisible: false},
{key: 5, data: {}, qText: {}, isVisible: false},
{key: 4, data: {}, qText: {}, isVisible: false}
]
function removeKey(array: any[], key: number, index: number = 0) {
let currentIndex = 0;
for (const currentKey in Object.keys(array)) {
if (values[currentKey].key === key) {
if (currentIndex < index) {
currentIndex++;
} else {
delete array[currentKey];
}
}
}
}
removeKey(values, 4, 2);
console.log(values);
请注意,这会改变原始数组。如果要返回一个新数组,则还必须应用深度克隆方法。
答案 1 :(得分:1)
您可以使用filter()
创建一个新数组,而元素不符合条件。
const array = [
{key: 4, data: {}, qText: {}},
{key: 4, data: {}, qText: {}, isVisible: false},
{key: 5, data: {}, qText: {}, isVisible: false},
{key: 4, data: {}, qText: {}, isVisible: false}
];
const result = array.filter((obj, index) => !(obj.key == 4 && index > 2));
console.log(result);
如果您不想创建一个新数组,而是想修改现有数组,我建议使用反向for循环。使用splice()
删除元素。逆转循环非常重要,因为移除元素时元素会移动。反转循环仍会移动元素,但已处理/迭代了移位元素。
const array = [
{key: 4, data: {}, qText: {}},
{key: 4, data: {}, qText: {}, isVisible: false},
{key: 5, data: {}, qText: {}, isVisible: false},
{key: 4, data: {}, qText: {}, isVisible: false}
];
for (let i = array.length - 1; i > 2; --i) {
if (array[i].key == 4) array.splice(i, 1);
}
console.log(array);
答案 2 :(得分:0)
您可以slice
在所需索引之后,然后使用谓词(lambda)函数find
index
。找到该项目之后,找到该项目的index
。如果-1
大于const data = [
{ key: 4, data: '', qText: '' },
{ key: 4, data: '', qText: '', isVisible: false },
{ key: 5, data: '', qText: '', isVisible: false },
{ key: 4, data: 'Delete me!', qText: '', isVisible: false }
];
const remove = (list, predicate, fromIndex = 0) => {
const found = list.slice(fromIndex).find(item => predicate(item));
const index = list.indexOf(found);
if (index > -1) list.splice(index, 1); // Remove
return list;
}
console.log(remove(data, item => item.key === 4, 2));
,我们将其删除。
.as-console-wrapper { top: 0; max-height: 100% !important; }
findIndex
注意事项::由于我们要在特定索引之后对列表进行切片,因此不能使用const remove = (list, predicate, fromIndex = 0) => {
const foundIndex = list.slice(fromIndex).findIndex(item => predicate(item));
if (foundIndex > -1) list.splice(foundIndex + fromIndex, 1); // Remove
return list;
}
,因为那样会返回切片数组中的索引。可以进行修改以考虑偏移量。
rbreak