js arr 转树状结构

213 阅读1分钟
array2tree(arr) {
    // 一级 非一级
    let top = [], sub = [], tempObj = {};
    arr.forEach(function (item) {
      if (item.parentCode == null || item.parentCode == '') { // 顶级分类
        top.push(item)
      } else {
        sub.push(item) // 其他分类
      }
      item.children = []; // 默然添加children属性
      tempObj[item.officeCode] = item // 用当前分类的id做key,存储在tempObj中
    })
    sub.forEach(function (item) {
      // 取父级
      let parent = tempObj[item.parentCode] || {'children': []}
      // 把当前分类加入到父级的children中
      parent.children.push(item)
    })

    return top
  }