后台返回的数据列表转化成树形结构的数据:
data为数据源
id为单个数据的id 默认id
parentId为父节点的id 默认parentId
children 为孩子节点的字段 默认children
export function handleTreelike(data, id, parentId, children) {
let config = {
id: id || 'id',
parentId: parentId || 'parentId',
childrenList: children || 'children'
};
let chiildrenListMap = {};
let nodeIds = {};
let tree = [];
for (let d of data){
let parentId = d[config.parentId];
if(chiildrenListMap[parentId] == null) {
chiildrenListMap[parentId] = []
}
nodeIds[d[config.id]] = d;
chiildrenListMap[parentId].push(d);
}
for(let d of data) {
let parentId = d[config.parentId];
if(nodeIds[parentId] == null) {
tree.push(d);
}
}
for(let t of tree) {
adaptToChildrenList(t);
}
function adaptToChildrenList(o) {
if(chiildrenListMap[o[config.id]] !== null) {
o[config.childrenList] = chiildrenListMap[o[config.id]];
}
if(o[config.childrenList]) {
for(let c of o[config.childrenList]) {
adaptToChildrenList(c)
}
}
}
return tree
}