F
F
fessss2020-12-25 15:04:51
JavaScript
fessss, 2020-12-25 15:04:51

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);
    },


But here's how to do the removal. I can't understand at all.
Tried like this but it doesn't work
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

2 answer(s)
A
Aetae, 2020-12-25
@fessss

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;
}

S
Swert, 2020-12-25
@swert-tech

Why write extra functions when vue has splice()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question