遍歷樹結構,當節點的children為空時,刪除children


需求

如果children為空數組,則刪除children

數據結構

let arr2=[{
          label: '一級 1',
          children: [{
            label: '二級 1-1',
            children: []
          }]
        }, {
          label: '一級 2',
          children: [{
            label: '二級 2-1',
            children: [{
              label: '三級 2-1-1'
            }]
          }, {
            label: '二級 2-2',
            children: [{
              label: '三級 2-2-1'
            }]
          }]
        }, {
          label: '一級 3',
          children: []
        }]

 

函數

 // children為[],則刪除children鍵
  function deleteChildren(arr) {
      let childs = arr
      for (let i = childs.length; i--; i > 0) {
        if (childs[i].children) {
          if (childs[i].children.length) {
            this.deleteChildren(childs[i].children)
          } else {
            delete childs[i].children
          }
        }
      }
      return arr
    }

 

調用

let arrNew = deleteChildren(arr2)
console.log(arrNew)

 



轉載自::https://www.jianshu.com/p/555a176bd8ee


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM