js去除数组中对象某个属性

适用场景:类似树状图的数组中对象的children属性,数组长度是否为0,若为0,则去除该节点,反之,保留改属性

通过递归方式实现,主要代码如下:

let arr = [

{id:1,lable:"父节点",children:[{id:11,lable:"子节点1"}]},
{id:2,lable:"父节点2",children:[{id:11,lable:"子节点1"},{id:11,lable:"子节点1-2",children:[{id:111,lable:"子节点1-2-1"}]}]},
]
let newArr = isChildrenFun(arr)
function isChildrenFun(arr){
     
      if (arr.length) {
        for (let i in arr) {
          if (arr[i].children.length) {
            isChildrenFun(arr[i].children)
          } else {
            delete arr[i].children;
          }
        }
      }
      return arr
    }

 

posted on 2020-08-14 09:36  婧星  阅读(7175)  评论(0编辑  收藏  举报

导航