猿问

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

我有一个一维深度嵌套数组:


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     

在这里,如果我删除一个节点(比如父节点),那么它的所有嵌套子节点(直到子子节点)都应该被删除。那么我怎样才能使用递归来做到这一点呢?


温温酱
浏览 91回答 1
1回答

长风秋雁

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);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答