Skip to content

Instantly share code, notes, and snippets.

@ygmpkk
Created October 14, 2021 05:53
Show Gist options
  • Save ygmpkk/8b27c1a8fef471bc363f83dd15fcaef0 to your computer and use it in GitHub Desktop.
Save ygmpkk/8b27c1a8fef471bc363f83dd15fcaef0 to your computer and use it in GitHub Desktop.
tree to list and list to tree
const toList: any = ({ childrens, ...data }: any) => {
return (childrens || []).reduce(
(prev: any[], { childrens, ...curr }: any) => {
if (childrens?.length) {
prev = prev.concat(recursionFlatten({ childrens, ...curr }))
} else {
prev = prev.concat(curr)
}
return prev
},
[data],
)
}
const toTree = (data: any[]) => {
const idMapping = data.reduce((prev, curr, index) => {
prev[curr.departmentid] = index
return prev
}, {})
let root
data.forEach((item) => {
if (item.parentid === 0) {
root = item
return
}
const parent = data[idMapping[item.parentid]]
parent.childrens = [...(parent.childrens || []), item]
})
return root
}
const flattenData = toList(data[0], data[0].childrens)
console.log(flattenData)
console.log('toTree:', toTree(flattenData))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment