import { v4 } from 'uuid'; type Arr = Record[] export const flatten = (source: Arr) => { const arr: Arr = [] const recursion = (source: Arr, pid: string | null) => { source.forEach(item => { const { children, ...rest } = item const id = v4() arr.push({ ...rest, pid, id }) if (children && children.length) { recursion(children, id) } }); } recursion(source, null) return arr } export const unflatten = (source: Arr) => { const arr: Arr = [] const obj: Record = {} source.forEach(item => { const { pid } = item if (!pid) { arr.push(item) } else { if (!obj[pid]) { obj[pid] = [] } obj[pid].push(item) } }) source.forEach(item => { const { id } = item const childs = obj[id] if (childs) { item.children = childs } }) return arr }