构造树型结构数据函数
function handleTree(data, id, parentId, children, rootId) {
id = id || 'id'
parentId = parentId || 'parentId'
children = children || 'children'
rootId = rootId || 0
//对源数据深度克隆
const cloneData = JSON.parse(JSON.stringify(data))
//循环所有项
const treeData = cloneData.filter(father => {
let branchArr = cloneData.filter(child => {
//返回每一项的子级数组
return father[id] === child[parentId]
});
branchArr.length > 0 ? father.children = branchArr : '';
//返回第一层
return father[parentId] === rootId;
});
return treeData != '' ? treeData : data;
}
参数说明
参数名 | 参数类型 | 数据含义 | 是否必填 | 默认值 |
---|
data | Array | 需转化的平整型数据 | 是 | 无 |
id | String | 主键id字段名 | 否 | ‘id’ |
parentId | Sring | 关联父级主键id字段名 | 否 | ‘parentId’ |
children | String | 保存子节点字段名 | 否 | ‘childrenId’ |
rootId | String | 根id | 否 | 0 |
示例
var list = [
{id:1, pid:0, name:'父亲'},
{id:2, pid:1, name:'儿子1'},
{id:3, pid:1, name:'儿子2'},
{id:4, pid:1, name:'儿子3'},
{id:5, pid:1, name:'儿子4'},
{id:6, pid:2, name:'孙子1-1'},
{id:7, pid:2, name:'孙子1-2'},
{id:8, pid:4, name:'孙子3-1'}
]
var tree = handleTree(list,'id','pid');
/* tree
[{
id:1, pid:0, name:'父亲',
children:[
{
id:2, pid:1, name:'儿子1',
children:[
{id:6, pid:2, name:'孙子1-1'},
{id:7, pid:2, name:'孙子1-2'}
]
},
{id:3, pid:1, name:'儿子2'},
{
id:4, pid:1, name:'儿子3',
children:[
{id:8, pid:4, name:'孙子3-1'}
]
},
{id:5, pid:1, name:'儿子4'},
]
}]
*/