遍历树形数据,删除其空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: []
        }]

 

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)

 

posted @ 2022-06-14 15:32  86727515  阅读(327)  评论(0编辑  收藏  举报