【vue】 将扁平化数组结构数据处理为tree对象数组并对tree对象进行排序

/**
 * 将扁平化数据结构处理为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);
        }
    });
}

猜你喜欢

转载自blog.csdn.net/THcoding_Cat/article/details/113697354