记录下自己常用的树形结构操作方法

根据ID删除当前树节点

function removeNode(arr, id){
   arr.forEach((v, k) => {
     if (v.id == id) {
       if (arr instanceof Array) {
         for (var i = 0; i < arr.length; i++) {
           if (arr[i].id == id) {
             arr.splice(i,1);
             i--;
           }
         }
       }
       arr.splice(i,1);
     } else {
       if (v.children) {
         removeNode(v.children, id);
       }
     }
   })
   return arr;
 } 

树转一维数组

tree2array: function (tree, child) {
  let lists = [];
  let toArr = function (children, child) {
    for (var i = 0; i < children.length; i++) {
      var c = children[i][child];
      lists.push(children[i]);

      if (c && c.length > 0) {
        toArr(c, child);
      }
    }
  }

  toArr(tree, child);
  return lists;
}

猜你喜欢

发表评论

最新发布