export const listToTree = (list, startPid = 0, varId = "id", varPid = "pid", varChildren = "children") => {
list = JSON.parse(JSON.stringify(list))
let getChildren = (pid) => {
let findChildren = list.filter(item => item[varPid] == pid)
if (findChildren.length) {
findChildren = findChildren.map(item => {
item[varChildren] = getChildren(item[varId])
return item
})
}
return findChildren
}
return getChildren(startPid)
}
export const treeToList = (tree, startPid = 0, varId = "id", varPid = "pid", varChildren = "children") => {
let children = JSON.parse(JSON.stringify(tree))
let returnList = [];
let eachToList = (children, pid) => {
children.forEach(item => {
let eachItem = {}
Object.keys(item).map(keyName => {
if (keyName !== varChildren) {
eachItem[keyName] = item[keyName]
}
})
eachItem[varPid] = pid;
returnList.push(eachItem)
if (item[varChildren] && item[varChildren].length) {
eachToList(item[varChildren], item[varId])
}
})
};
eachToList(children, startPid)
return returnList
}
网友评论