亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

刪除深度嵌套一維數組中的所有嵌套子節點

刪除深度嵌套一維數組中的所有嵌套子節點

溫溫醬 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 關注
  • 115 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號