一维父子关系数组与树形结构互相转换

走远了吗. 提交于 2019-11-29 14:14:25
//非递归1 思路:第一次循环是作为父节点循环,第二次循环是子节点嵌套在父节点循环中,处理两种情况;当子id===父parendId时;parendId===0作为根节点的子节点时var data=[
  { id: 40, parentId: 31, note: "的萨达是" }, 

  { id: 20, parentId: 11, note: "的萨达是" },
  { id: 22, parentId: 20, note: "dsadas" },
  { id: 12, parentId: null, note: "dsadasad萨达s" }, 
  { id: 11, parentId: undefined, note: "dqwds" }, 
  { id: 24, parentId: 22, note: "搜索" },
  { id: 34, parentId: 22, note: "搜索" }
]
function mygetTree(data,idName='id',parentIdName='parentId'){  //深克隆
    let arr=JSON.parse(JSON.stringify(data));  //添加_level层级属性
    arr.forEach(node=>{node._level=1;!node[parentIdName]&&(node[parentIdName]=0)});  //parenId排序防止_level属性错误
    arr=arr.sort((a,b)=>{return a[parentIdName]-b[parentIdName]})
    return arr.reduce((tree,node,index)=>{
        let childNode=arr.filter(child=>{
            return (child[parentIdName]===node[idName])&&(child._level=node._level+1)
        })
        node.children=childNode.length?childNode:[];
        if(!node[parentIdName]){
            tree.children=tree.children?[...tree.children,node]:[node]
        }
        return tree
    },{})
}
//非递归2 利用对象,将父id添加children;然后通过这个对象组装即可
let allRes = [    {id: 1, title: "公司",expand:true, pid: 0},    {id: 60, title: "总经理",expand:true, pid: 1},    {id: 66, title: "业务1部",expand:true, pid: 1},    {id: 76, title: "总经理助理1", expand:true,pid: 60},    {id: 77, title: "总经理助理2", expand:true,pid: 66},    {id: 63, title: "财务部",expand:true, pid: 1},    {id: 64, title: "会计", expand:true, pid: 63},    {id: 65, title: "出纳",expand:true,  pid: 63},    {id: 68, title: "总监",expand:true, pid: 66},    {id: 70, title: "总监", expand:true,pid: 67},    {id: 81, title: "test",expand:true, pid: 67},    {id: 71, title: "业务员",expand:true, pid: 66},    {id: 75, title: "会计员", expand:true, pid: 64}];

let result = allRes.reduce(function(prev, item) {    prev[item.pid] ? prev[item.pid].push(item) : prev[item.pid] = [item];    return prev;}, {});for (let prop in result) {    result[prop].forEach(function(item, i) {        result[item.id] ? item.children = result[item.id] : ''    });}result = result[0];
或者递归
const toTree =
  (arr, pID) =>
    arr
      .filter(({ parentId }) => parentId == pID)
      .map(a => ({
        ...a,
        childers: toTree(arr.filter(({ parentId }) => parentId != pID), a.id)
      }))

 

 参考:https://segmentfault.com/q/1010000017234194

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!