排序相关逻辑
1.生成排序函数 generateSortFn
function generateSortFn(sortField, asc) {
return (a, b) => {
const valueA = a[sortField]
const valueB = b[sortField]
if (valueA > valueB) {
if (asc) {
return 1
}
return -1
}
if (asc) {
return -1
}
return 1
}
}
2. 数组根据函数进行排序 sortData(data, sortFun)
function sortData(data, sortFun) {
data.sort(sortFun)
}
3.对树进行排序(通过自定义函数) sortTreeByFunction
export const sortTreeByFunction = function (treeData, sortFun) {
sortData(treeData, sortFun)
treeData.forEach((item) => {
const children = item.children
if (children && children.length > 0) {
sortData(children, sortFun)
sortTreeByFunction(children, sortFun)
}
})
return treeData
}
4.对树进行排序(通过字段)
export const sortTreeByField = function (treeData, sortField, asc = true) {
return sortTreeByFunction(treeData, generateSortFn(sortField, asc))
}
树形结构数据和数组结构数据相互转化
1.数组结构转化成树结构
export const arrayToTree = function (
data = [],
invalId = [],
id = 'id',
parentId = 'parentId',
) {
const result = []
const dataTemp = cloneDeep(data)
dataTemp.forEach((item) => {
if (!item.children) {
item.children = []
}
if (invalId.includes(item[id]))
return
const parentIdValue = item[parentId]
if (!parentIdValue) {
item._level = 1
result.push(item)
}
else {
const parent = find(dataTemp, node => node[id] === parentIdValue)
if (!parent) {
item._level = 1
result.push(item)
return
}
if (!parent.children) {
parent._level = parent._level ? parent._level : 1
parent.children = []
}
item._level = parent._level + 1
parent.children.push(item)
}
})
return result
}
2.树转化数组
export const treeToArray = function (treeData = [], childsKey = 'children') {
let result = []
Array.from(treeData).forEach((record) => {
result.push(record)
if (record[childsKey] && record[childsKey].length > 0) {
const children = treeToArray(record[childsKey], childsKey)
result = result.concat(children)
}
})
return result
}
3.树的最后一级转化为数组
export const treeFinalToArray = function (treeData) {
let result = []
Array.from(treeData).forEach((record) => {
if (record.childNodes && record.childNodes.length > 0) {
const children = treeFinalToArray(record.childNodes)
result = result.concat(children)
}
else {
result.push(record.data)
}
})
return result
}
4.树对象转化数组
4
export const treeObjToArray = function (
treeObject = {},
childKey = 'children',
) {
let result = []
result.push(treeObject)
if (treeObject[childKey]) {
const children = treeObjToArray(treeObject[childKey], childKey)
result = result.concat(children)
}
return result
}
查询问题分类路径数据
export function arrayTreePathData(id, data) {
const item = {
problemCategoryLevelId: [],
problemCategoryLevelIds: [],
}
data.forEach((itema) => {
itema.children.forEach((itemb) => {
itemb.children.forEach((itemc) => {
itemc.children.forEach((itemd) => {
if (itemd.id === id) {
item.problemCategoryLevelIds = [itema.id, itemb.id, itemc.id]
item.problemCategoryLevelId = [itema.name, itemb.name, itemc.name]
}
})
})
})
})
return item
}