相信你们开发中确定遇到过将无层级的列表转换为层级关系树的问题,解决思路是根据父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;
}
}复制代码