根據parentId將列表轉換爲層級樹結構

        相信你們開發中確定遇到過將無層級的列表轉換爲層級關係樹的問題,解決思路是根據父id一層一層遍歷生成層級樹,下面是我開發中用的方法,歡迎你們提出優化改進的意見。node

        原始數據結構以下安全

list:[
    {name:"消防安全技術服務有限公司",id:1,parentId:0},
    {name:"測試12",id:2,parentId:1},
    {name:"l測試123",id:3,parentId:1},
    {name:"研發中心",id:11,parentId:1},
    {name:"iOS開發測試",id:12,parentId:1},
    {name:"美團點評",id:14,parentId:1},
    {name:"華北大區",id:15,parentId:14},
    {name:"華東大區",id:17,parentId:14},
    {name:"無線產品部測試",id:33,parentId:1},
    {name:"華南大區",id:35,parentId:14},
    {name:"中南大區",id:36,parentId:14},
    {name:"北京區域",id:37,parentId:15},
    {name:"遼寧區域",id:38,parentId:15},
    {name:"河南區域",id:39,parentId:15},
    {name:"黑吉區域",id:40,parentId:15},
    {name:"中西區域",id:41,parentId:15},
    {name:"北京配送1組",id:42,parentId:17},
    {name:"北京配送2組",id:43,parentId:17},
    {name:"北京配送3組",id:44,parentId:17},
],  複製代碼

轉換後數據以下:bash

[
      {
	"id": 1,
	"parentId": 0,
	"name": "消防安全技術服務有限公司",
	"children": [
            {
		"id": 14,
		"parentId": 1,
		"name": "美團點評",
		"children": []
             },
             {
                 .........
	      }
         ]
       }
]複製代碼

閒話很少說,上代碼數據結構

const defaultTreeProps = {   //配置項
     key: 'id',
     parentKey: 'parentId',
     label: 'name',
     children: 'children',
     rootValue: 0,
     stopKey: 'type',// 中止位
     stopValue: 'sdfadfytuya',// 中止值
},
buildTree(list, treeProps , root) {
    if (!root) {
        root = {};
        root[treeProps.key] = treeProps.rootValue;
        root[treeProps.children] = [];
    }
    if (list && list.length > 0) {
            let children = root[treeProps.children];
            list.forEach(node => {
                if (node[treeProps.parentKey] === root[treeProps.key]) {
                    if (!children) {
                        children = [];
                        root[treeProps.children] = children;
                    }
                    let copyNode = {};
                    copyNode[treeProps.key] = node[treeProps.key]; 
                    copyNode[treeProps.parentKey] = node[treeProps.parentKey];
                    copyNode[treeProps.label] = node[treeProps.label];
                    copyNode[treeProps.children] = node[treeProps.children];
                    copyNode[treeProps.stopKey] = node[treeProps.stopKey];
                    children.push(copyNode);
                }
            });
            if (children && children.length > 0) {
                list = list.filter(item1 => !children.some(item2 => item2[treeProps.key] === item1[treeProps.key]));
                children.forEach(node => {
                    if (root[treeProps.stopKey] !== treeProps.stopValue) {
                        // 遞歸
                        buildTree(list, treeProps, node);
                    }
                });
            }
            return root.children;
      } else {
            return root.children;
      }

}複製代碼
相關文章
相關標籤/搜索