Vue3组合式API:递归删除嵌套数组指定ID的元素
问题:Vue3中递归删除嵌套数组指定ID的元素(含子元素)
我用vue-draggable构建多级导航菜单,生成的数组支持N层嵌套,需要实现根据ID删除指定对象,且删除父元素时一并删除其子元素。
数组结构示例:
[ { "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": [] } ]
之前尝试过针对嵌套对象的删除方案,但因为我的数据顶层是数组,方案不生效。当前用Vue3组合式API编写的部分代码如下:
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 } }
正确实现方案
核心思路是递归遍历数组,过滤掉目标ID的元素,同时对每个元素的子数组做同样的递归处理。因为顶层是数组,需要单独处理顶层逻辑,再递归处理子元素。
修改后的代码如下:
setup(props, context) { const resources = ref(props.data) // 递归删除指定ID的元素(含子元素) const removeById = (items, targetId) => { // 过滤当前层级的元素,保留不等于目标ID的项 return items.filter(item => { // 如果当前项不是目标ID,继续递归处理它的子元素 if (item.id !== targetId) { item.children = removeById(item.children, targetId) return true } // 如果是目标ID,直接过滤掉(子元素也会被一并删除) return false }) } const remove = (element) => { // 对顶层数组执行删除操作 resources.value = removeById([...resources.value], element.id) } return { resources, remove } }
代码说明
removeById函数接收当前层级的数组和目标ID,返回过滤后的数组:- 用
filter遍历当前数组,判断每个元素的ID是否等于目标ID - 如果不是目标ID,递归处理该元素的
children数组,更新其children属性,同时保留该元素 - 如果是目标ID,直接过滤掉,其下的子元素也会被一并移除(因为父元素都被过滤了,子元素自然不会保留)
- 用
remove方法中,传入要删除的元素的ID,调用removeById处理顶层数组,并更新resources的值
这样就能实现根据ID递归删除任意层级的元素,且删除父元素时自动删除所有子元素的需求。
内容的提问来源于stack exchange,提问作者Luciano
相关产品推荐
相关产品推荐

