/**
* 将扁平化数据结构处理为tree结构
* @param { 扁平化数据结构 } obj
*/
export function formatTree(obj){
let copyedObj = JSON.parse(JSON.stringify(obj)); //深拷贝源数据
return copyedObj.filter(parent =>{
let findChildren = copyedObj.filter(child => {
return parent.id === child.parentId;
})
findChildren.length > 0 ? parent.children = findChildren : parent.children = []
return parent.parentId == undefined
})
}
此处为根据tree结构对象中的location值的大小进行排序
/**
* 树结构list排序
* @param { tree结构list } list
*/
export function sortList(list){
list.sort((obj1, obj2) => {
obj1.location = obj1.location || 255;
obj2.location = obj2.location || 255;
let val1 = Number(obj1.location);
let val2 = Number(obj2.location);
if (val1 < val2) {
return -1;
} else if (val1 > val2) {
return 1;
} else {
return 0;
}
}).forEach(v => {
if(v.children){
sortList(v.children);
}
});
}