Recursion 按对象id筛选嵌套树对象

Recursion 按对象id筛选嵌套树对象,recursion,filter,Recursion,Filter,我有一个树对象,如下所示: let data = [ { id: 1, children: [ { id: 1.1, children: [ { id: 1.2, children: [] }, { id: 1.22, children: [] } ] } ] }, { id:

我有一个树对象,如下所示:

let data = [
  {
    id: 1,
    children: [
     {
      id: 1.1,
      children: [
       {
        id: 1.2,
        children: []
       },
       {
        id: 1.22,
        children: []
        }
      ]
     }
    ]
  },
  {
   id: 2,
   children: []
  }
]
let data = [
  {
    id: 1,
    children: [
     {
      id: 1.1,
      children: [
        {
         id: 1.22,
         children: []
        }
      ]
     }
    ]
  },
  {
   id: 2,
   children: []
  }
]
我想过滤掉等于特定值的id。在这种情况下,我想过滤掉id equal1.2

我想要的结果如下:

let data = [
  {
    id: 1,
    children: [
     {
      id: 1.1,
      children: [
       {
        id: 1.2,
        children: []
       },
       {
        id: 1.22,
        children: []
        }
      ]
     }
    ]
  },
  {
   id: 2,
   children: []
  }
]
let data = [
  {
    id: 1,
    children: [
     {
      id: 1.1,
      children: [
        {
         id: 1.22,
         children: []
        }
      ]
     }
    ]
  },
  {
   id: 2,
   children: []
  }
]
我搜索了一些关于过滤嵌套深度对象的问题,但仍然不知道如何搜索。我需要使用递归来解决这个问题

这是我的方式:

function handleDelete (data) {
 return data.filter(t => {
   if (t.children.length) {
     handleDelete(t.children)
    })
   } else {
     return t.id !== '1.2'
  }
})
}
let result = handleDelete(data)

删除节点及其子节点

下面是一种使用
flatMap
和交互递归的有效技术1-

  • del
    接受一个节点数组
    t
    、一个查询
    q
    ,并在每个带有查询的节点上调用
    del1
  • del1
    接受单个节点、
    t
    、查询、
    q
    ,并对节点的子节点调用
    del
  • constdel=(t,q)=>
    t、 平面图(v=>del1(v,q))//
    q==t.id
    ? []
    
    :{……t,children:del(t.children,q)}//我花了几个小时才明白你的意思。你能解释更多关于
    对象(t)==t
    ,如何检查是对象吗?构造函数对象(),它是什么意思?感谢[我找到了这个关于对象(obj)==objCorrect的链接,这是一种检查
    t
    是否是对象的方法。但是,运行时类型检查,如
    Array.isArray(t)
    Object(t)===t
    有点笨重,有时可能表示函数试图做太多的事情。第一个程序通过使用每个都能做一件事情的较小函数的组合来避免类型检查。