js 数组扁平化和树之间相互转换

function main() {
  let data = [
    {id:"00", name: "李大大", pid:"", job: "项目经理1"},
    {id:"01", name: "张大大", pid:"", job: "项目经理2"},
    {id:"001", name: "王大大", pid:"", job: "项目经理3"},
    {id:"02", name: "小亮", pid:"01", job: "产品leader"},
    {id:"03", name: "小美", pid:"01", job: "UIleader"},
    {id:"04", name: "老马", pid:"00", job: "技术leader"},
    {id:"05", name: "老王", pid:"00", job: "测试leader"},
    {id:"06", name: "老李", pid:"001", job: "运维leader"},

    {id:"07", name: "小丽", pid:"02", job: "产品经理"},
    {id:"08", name: "大光", pid:"02", job: "产品经理"},
    {id:"09", name: "小高", pid:"03", job: "UI设计师"},
    {id:"10", name: "小刘", pid:"04", job: "前端工程师"},
    {id:"11", name: "小华", pid:"04", job: "后端工程师"},
    {id:"12", name: "小李", pid:"04", job: "后端工程师"},
    {id:"13", name: "小赵", pid:"05", job: "测试工程师"},
    {id:"14", name: "小强", pid:"05", job: "测试工程师"},
    {id:"15", name: "小涛", pid:"06", job: "运维工程师"}
  ];

  //数组转树
  function arr2Tree(list) {
    let resultList = []
    let sourceMap = {}
    list.forEach(item => {
      sourceMap[item.id] = item
    })

    list.forEach(item => {
      let parent = sourceMap[item.pid]
      if (parent) {
        (parent.children || (parent.children = [])).push(item)
      } else {
        resultList.push(item)
      }
    })
    return resultList;
  }
  let treeArr = arr2Tree(data)
  console.log(treeArr)
  console.log(treeArr.flat(Infinity))

  //扁平化树
  function tree2Arr(tree) {
    let sourceTree = JSON.parse(JSON.stringify(tree))
    return sourceTree.reduce((pre, cur) => {
      pre = pre.concat(cur).concat(cur.children && cur.children.length > 0 ? tree2Arr(cur.children) : [])
      delete cur.children
      return pre
    }, [])
  }
  let dd = tree2Arr(treeArr)
  console.log(dd)
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值