Home > OS >  Remove object from nested array with recursion
Remove object from nested array with recursion

Time:10-04

I'm working with vue-draggable for creating a navigation menu. The result array could have N deep levels. I want to remove an object by it's id.

The array looks like:

[
  {
    "id": 1,
    "name": "Viedma",
    "slug": "viedma",
    "children": []
  },
  {
    "id": 6,
    "name": "Cultura",
    "slug": "Cultura",
    "children": [
      {
        "id": 2,
        "name": "Rio Negro",
        "slug": "rio-negro",
        "children": [
          {
            "id": 4,
            "name": "Edictos",
            "slug": "edictos",
            "children": []
          },
          {
            "id": 5,
            "name": "Deportes",
            "slug": "deportes",
            "children": []
          }
        ]
      }
    ]
  },
  {
    "id": 3,
    "name": "Policiales",
    "slug": "policiales",
    "children": []
  }
]

I've tried the solution from remove object from nested array but since I have an array instead of a main object it doesn't work.

Please note that I'm using vue 3 with composition API. This is what I have so far. The remove() method is called from UI

setup(props, context) {
    const resources = ref(props.data)

    const removeFromTree = (parent, childNameToRemove) => {
      parent.children = parent.children
          .filter(function(child){ return child.name !== childNameToRemove})
          .map(function(child){ return removeFromTree(child, childNameToRemove)})
      return parent
    }

    const remove = (element) => {
      var tree = [...resources.value]
      resources.value = removeFromTree(tree, element.name)
    }

    return {
      resources,
      remove
    }
  }

BTW, If parent is removed, all it's children should be removed too.

CodePudding user response:

Your function takes parent as an object but you passing tree as an array. You can do like this

function removeItemByName(items, itemName) {
 return items.filter(item => item.name !== itemName)
   .map(item => {
     item.children = removeItemByName(item.children, itemName)
     return item
   })
}

const input = [
  {
    "id": 1,
    "name": "Viedma",
    "slug": "viedma",
    "children": []
  },
  {
    "id": 6,
    "name": "Cultura",
    "slug": "Cultura",
    "children": [
      {
        "id": 2,
        "name": "Rio Negro",
        "slug": "rio-negro",
        "children": [
          {
            "id": 4,
            "name": "Edictos",
            "slug": "edictos",
            "children": []
          },
          {
            "id": 5,
            "name": "Deportes",
            "slug": "deportes",
            "children": []
          }
        ]
      }
    ]
  },
  {
    "id": 3,
    "name": "Policiales",
    "slug": "policiales",
    "children": []
  }
]

console.log(removeItemByName(input, 'Policiales'))
console.log(removeItemByName(input, 'Deportes'))

  • Related