Answer the question
In order to leave comments, you need to log in
How to correctly remove an object from an array by key?
I have a method that creates builds a treeview
addChild(item) {
this.companyShow = true;
this.selectedItem = item;
},
addCompany() {
if (!this.selectedItem.children) {
this.$set(this.selectedItem, 'children', []);
}
const name = this.company;
// eslint-disable-next-line no-plusplus
const id = this.nextId++;
this.selectedItem.children.push({
id,
name,
});
this.company = '';
this.companyShow = false;
this.$refs.tree.updateAll(true);
},
removeChild(items, i) {
return items.map((item) => ({ ...item })).filter((item) => {
if ('children' in item) {
item.children = this.removeChild(item.children, i.id);
}
return item.id !== i.id;
});
},
Answer the question
In order to leave comments, you need to log in
Learn js basics please.
removeChild(items, child) {
if(!Array.isArray(items) || !child)
return items;
for(let i = items.length; i--;) {
const { id, children } = items[i];
if(id === child.id)
items.splice(i, 1);
else
this.removeChild(children, child);
}
return items;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question