/**
* 将扁平化数据结构处理为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);
}
});
}
这篇博客探讨了如何将扁平化的数据结构转换成树形结构,并对树结构的节点依据特定的location属性进行排序。主要涉及两个关键函数:`formatTree`用于构建树形结构,而`sortList`则实现了按location值排序。这些方法对于数据组织和处理至关重要,特别是在前端展示和数据操作中。
374





