javascript将平行的拥有上下级关系的数据转换成树形结构

转换函数

var Littlehow = {};
/**
 * littlehow 2019-05-15
 * 平行数据树形转换器
 * @type {{format: tree.format, sort: tree.sort, map: (function(*, *): {root, da})}}
 */
Littlehow.tree = {
    /**
     *  将平行结果转换成树形结构,父编号不可为空,如果为最高,则可以设置root等字样
     *  如果有排序字段,将排序完成后返回
     *  如:data:[{id:'1', parentId:'root', name:'test'}, {id:'2', parentId:'1', name:'test1'},{id:'3', parentId:'1', name:'test2'}]
     *     format:{id:'id', root:'root', 'pid':'parentId', child:'children'}
     *  解析后的数据形式为:
     *  [{id:'1','parentId':'root',name:'test', children:[{id:'2',parentId:'1',name:'test1'},{id:'3',parentId:'1',name:'test2'}]}]
     *  @param data   -- 需要转换的数据
     *  @param format -- 转换格式 {id:'', root:'', pid:'', child:'', sort:{field:'', direct:1}}
     *  @return {*} 转换后的数据
     */
    format : function(data, format) {
        //如果data,没有数据,则将data原样返回
        if (!data || data.length <= 0) return data;
        var map = this.map(data, format);
        //再遍历原数据进行树形填充
        for (var i = 0, len = data.length; i < len; i++) {
            var d = data[i];
            if (map.dm[d[format.pid]]) {
                map.dm[d[format.pid]][format.child].push(d);
            }
        }
        //最后将root排序后返回
        this.sort(map.root, format);
        return map.root;
    },
    /**
     * 平行数据映射为map
     * @param data     -- 平行数据
     * @param format   -- tree格式化信息
     * @return {{d, root}}  -- 返回数据和根数据map
     */
    map : function(data, format) {
        var dataMap = {};//全数据映射
        var root = [];//根
        for (var i = 0, len = data.length; i < len; i++) {
            var d = data[i];
            //初始化child字段,如果不想要这里初始化也可以在树形填充出进行判断初始化
            d[format.child] = [];
            dataMap[d[format.id]] = d;
            if (data[i][format.pid] === format.root) {//将root记录到root数组
                root.push(d);
            }
        }
        return {dm : dataMap, root : root};
    },
    /**
     * 进行排序  format.sort格式为sort:{field:'', direct:1},其中direct=1为正序,direct=-1为逆序
     * @param result  -- 结果集
     * @param format  -- 格式化
     */
    sort : function(result, format) {
        if (!format.sort) return;//没有排序配置则不进行排序
        result.sort(function(a, b) {
            var as = a[format.sort.field];
            var bs = b[format.sort.field];
            return (as - bs) * format.sort.direct;
        });
        //如果result中有child,则继续进行排序
        for (var i = 0, len = result.length; i < len; i++) {
            if (result[i][format.child].length > 0) {
                this.sort(result[i][format.child], format);
            }
        }
    }
};

  

调用示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>tree case</title>
    <script src="TreeUtils.js" type="application/javascript"></script>
    <script type="application/javascript">
        var data = [
            {
                "menuName": "系统管理",
                "parentId": "root",
                "iconCls": "el-icon-s-tools",
                "request": null,
                "leaf": "0",
                "sortNo": 30,
                "menuId": "1"
            },
            {
                "menuName": "人员管理",
                "parentId": "1",
                "iconCls": null,
                "request": "/system/user",
                "leaf": "1",
                "sortNo": 3,
                "menuId": "2"
            },
            {
                "menuName": "角色管理",
                "parentId": "1",
                "iconCls": null,
                "request": "/system/role",
                "leaf": "1",
                "sortNo": 6,
                "menuId": "3"
            },
            {
                "menuName": "菜单管理",
                "parentId": "1",
                "iconCls": null,
                "request": "/system/menu",
                "leaf": "1",
                "sortNo": 9,
                "menuId": "4"
            },
            {
                "menuName": "系统配置",
                "parentId": "1",
                "iconCls": null,
                "request": "/system/config",
                "leaf": "1",
                "sortNo": 12,
                "menuId": "5"
            },
            {
                "menuName": "字典管理",
                "parentId": "1",
                "iconCls": null,
                "request": "/system/dictionary",
                "leaf": "1",
                "sortNo": 15,
                "menuId": "6"
            },
            {
                "menuName": "内容管理",
                "parentId": "root",
                "iconCls": "el-icon-tickets",
                "request": null,
                "leaf": "0",
                "sortNo": 18,
                "menuId": "21"
            },
            {
                "menuName": "banner",
                "parentId": "21",
                "iconCls": null,
                "request": "/content/banner",
                "leaf": "1",
                "sortNo": 3,
                "menuId": "22"
            },
            {
                "menuName": "公告列表",
                "parentId": "21",
                "iconCls": null,
                "request": "/content/attention",
                "leaf": "1",
                "sortNo": 9,
                "menuId": "23"
            },
            {
                "menuName": "App版本管理",
                "parentId": "root",
                "iconCls": "el-icon-tickets",
                "request": null,
                "leaf": "0",
                "sortNo": 27,
                "menuId": "91"
            },
            {
                "menuName": "App版本管理",
                "parentId": "91",
                "iconCls": null,
                "request": "/app/manager",
                "leaf": "1",
                "sortNo": 3,
                "menuId": "92"
            }
        ];

        var format = {
            id:'menuId', //菜单编号,作为树形查找id
            root:'root', //顶层节点的parentId是root
            pid:'parentId',//父节点标识字段为parentId
            child:'children',//构造出的树形子节点数组名为children
            sort:{field:'sortNo', direct:1}};//排序字段为sortNo,且正序

        var result = Littlehow.tree.format(data, format);
        console.log(result);
        document.write(JSON.stringify(result));
    </script>
</head>
<body>

</body>
</html>

  

输出结果如下

[{
	"menuName": "内容管理",
	"parentId": "root",
	"iconCls": "el-icon-tickets",
	"request": null,
	"leaf": "0",
	"sortNo": 18,
	"menuId": "21",
	"children": [{
		"menuName": "banner",
		"parentId": "21",
		"iconCls": null,
		"request": "/content/banner",
		"leaf": "1",
		"sortNo": 3,
		"menuId": "22",
		"children": []
	}, {
		"menuName": "公告列表",
		"parentId": "21",
		"iconCls": null,
		"request": "/content/attention",
		"leaf": "1",
		"sortNo": 9,
		"menuId": "23",
		"children": []
	}]
}, {
	"menuName": "App版本管理",
	"parentId": "root",
	"iconCls": "el-icon-tickets",
	"request": null,
	"leaf": "0",
	"sortNo": 27,
	"menuId": "91",
	"children": [{
		"menuName": "App版本管理",
		"parentId": "91",
		"iconCls": null,
		"request": "/app/manager",
		"leaf": "1",
		"sortNo": 3,
		"menuId": "92",
		"children": []
	}]
}, {
	"menuName": "系统管理",
	"parentId": "root",
	"iconCls": "el-icon-s-tools",
	"request": null,
	"leaf": "0",
	"sortNo": 30,
	"menuId": "1",
	"children": [{
		"menuName": "人员管理",
		"parentId": "1",
		"iconCls": null,
		"request": "/system/user",
		"leaf": "1",
		"sortNo": 3,
		"menuId": "2",
		"children": []
	}, {
		"menuName": "角色管理",
		"parentId": "1",
		"iconCls": null,
		"request": "/system/role",
		"leaf": "1",
		"sortNo": 6,
		"menuId": "3",
		"children": []
	}, {
		"menuName": "菜单管理",
		"parentId": "1",
		"iconCls": null,
		"request": "/system/menu",
		"leaf": "1",
		"sortNo": 9,
		"menuId": "4",
		"children": []
	}, {
		"menuName": "系统配置",
		"parentId": "1",
		"iconCls": null,
		"request": "/system/config",
		"leaf": "1",
		"sortNo": 12,
		"menuId": "5",
		"children": []
	}, {
		"menuName": "字典管理",
		"parentId": "1",
		"iconCls": null,
		"request": "/system/dictionary",
		"leaf": "1",
		"sortNo": 15,
		"menuId": "6",
		"children": []
	}]
}]

  

posted @ 2020-08-28 12:56  我是真的大米  阅读(465)  评论(0编辑  收藏  举报