部门调整为树结构
This commit is contained in:
57
src/common/tree.js
Normal file
57
src/common/tree.js
Normal file
@@ -0,0 +1,57 @@
|
||||
class Tree {
|
||||
constructor(list = [], config) {
|
||||
this.config = {
|
||||
key: 'id', parent: 'parentId', children: 'children',
|
||||
...config
|
||||
}
|
||||
this.list = list
|
||||
if (Array.isArray(list)) this.tree = this.arr2tree(list)
|
||||
}
|
||||
|
||||
arr2tree(list) {
|
||||
const {key, parent, children} = this.config
|
||||
const result = []
|
||||
this.map = {}
|
||||
const ids = list?.map(e => `#${e[key]}#`)?.toString()
|
||||
for (const e of list) {
|
||||
const id = e[key], pid = e[parent]
|
||||
this.map[id] = {...e, [children]: [this.map[id]?.[children]].flat().filter(Boolean)}
|
||||
const treeItem = this.map[id]
|
||||
if (!!pid && ids.indexOf(`#${pid}#`) > -1) {
|
||||
if (!this.map[pid]) {
|
||||
this.map[pid] = {
|
||||
children: []
|
||||
}
|
||||
}
|
||||
this.map[pid].children.push(treeItem)
|
||||
} else result.push(treeItem)
|
||||
}
|
||||
const removeNullChildren = node => {
|
||||
if (node[children] && node[children].length > 0) {
|
||||
node[children].map(c => removeNullChildren(c))
|
||||
} else delete node[children]
|
||||
}
|
||||
result.forEach(removeNullChildren)
|
||||
return result
|
||||
}
|
||||
|
||||
root(id) {
|
||||
return this.map[id]
|
||||
}
|
||||
|
||||
find(id) {
|
||||
return this.map[id]
|
||||
}
|
||||
|
||||
every(cb) {
|
||||
const iterate = list => {
|
||||
list?.map(e => {
|
||||
cb(e)
|
||||
iterate(e.children)
|
||||
})
|
||||
}
|
||||
iterate(this.tree)
|
||||
}
|
||||
}
|
||||
|
||||
export default Tree
|
||||
@@ -308,5 +308,31 @@ export default {
|
||||
qs,
|
||||
permissions,
|
||||
copy,
|
||||
reg
|
||||
reg,
|
||||
arr2tree(list, config = {}) {
|
||||
const {key = 'id', parent = 'parentId', children = 'children'} = config
|
||||
const result = []
|
||||
const itemMap = {}
|
||||
const ids = list?.map(e => `#${e[key]}#`)?.toString()
|
||||
for (const e of list) {
|
||||
const id = e[key], pid = e[parent]
|
||||
itemMap[id] = {...e, [children]: [itemMap[id]?.[children]].flat().filter(Boolean)}
|
||||
const treeItem = itemMap[id]
|
||||
if (!!pid && ids.indexOf(`#${pid}#`) > -1) {
|
||||
if (!itemMap[pid]) {
|
||||
itemMap[pid] = {
|
||||
children: []
|
||||
}
|
||||
}
|
||||
itemMap[pid].children.push(treeItem)
|
||||
} else result.push(treeItem)
|
||||
}
|
||||
const removeNullChildren = node => {
|
||||
if (node[children] && node[children].length > 0) {
|
||||
node[children].map(c => removeNullChildren(c))
|
||||
} else delete node[children]
|
||||
}
|
||||
result.forEach(removeNullChildren)
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user