为了账号安全,请及时绑定邮箱和手机立即绑定

删除深度嵌套一维数组中的所有嵌套子节点

删除深度嵌套一维数组中的所有嵌套子节点

温温酱 2023-07-29 11:10:02
我有一个一维深度嵌套数组:nestedObj: [   { id: 1, parentId: null, taskCode: '12', taskName: 'Parent one', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []},   { id: 2, parentId: 1, taskCode: '12100', taskName: 'Child one', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []},   { id: 3, parentId: 2, taskCode: '12200', taskName: 'SubChild one', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []},   { id: 4, parentId: 3, taskCode: '122001', taskName: 'Sub-dub-Child one', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []},   { id: 5, parentId: null, taskCode: '13', taskName: 'Parent two', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []}]如上面的数据结构,以taskName为树形视图如下所示-> Parent one        -> Child one                   -> SubChild one                                  ->Sub-sub-Child one-> Parent two     在这里,如果我删除一个节点(比如父节点),那么它的所有嵌套子节点(直到子子节点)都应该被删除。那么我怎样才能使用递归来做到这一点呢?
查看完整描述

1 回答

?
长风秋雁

TA贡献1757条经验 获得超7个赞

const nestedObj = [

   { id: 1, parentId: null, taskCode: '12', taskName: 'Parent one', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []},

   { id: 2, parentId: 1, taskCode: '12100', taskName: 'Child one', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []},

   { id: 3, parentId: 2, taskCode: '12200', taskName: 'SubChild one', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []},

   { id: 4, parentId: 3, taskCode: '122001', taskName: 'Sub-dub-Child one', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []},

   { id: 5, parentId: null, taskCode: '13', taskName: 'Parent two', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []}

];

function deepDelete(id) {

  const index = nestedObj.findIndex((element) => element.id === id);

  if (index === -1) return;

  

  nestedObj.splice(index, 1);

  

  const childElements = nestedObj.filter((element) => element.parentId === id);

  for (const element of childElements) {

    deepDelete(element.id);

  }

}


deepDelete(2);

console.log(nestedObj);


查看完整回答
反对 回复 2023-07-29
  • 1 回答
  • 0 关注
  • 90 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信