目的
实现类似于 RedisDesktopManager 中键名的 : 展示为树形结构的功能。
参考
实现
export interface TreeNode<T> {
label: string
data: T
children: TreeNode<T>[]
}
export function buildTree<T extends { [key: string]: any }, K extends keyof T>(data: T[], key: K, separator: string): TreeNode<T>[] {
const roots = [] as TreeNode<T>[]
for (const item of data) {
const paths = item[key] as string
let curr = roots
for (const path of paths.split(separator)) {
const temp = curr
for (const node of curr) {
if (node.label === path) {
curr = node.children
break
}
}
if (curr == temp) {
const root = { label: path, data: item, children: [] } as TreeNode<T>
curr.push(root)
curr = root.children
}
}
}
return roots
}
测试
import * as fs from 'fs'
import { buildTree } from '../lib'
const data = [
{ id: 1, name: '1' },
{ id: 2, name: '2:2-1' },
{ id: 3, name: '2:2-2' },
{ id: 4, name: '2:2-2:2-2-1' },
{ id: 5, name: '3:3-1' }
]
const result = buildTree(data, 'name', ':')
fs.writeFileSync('./tree.json', JSON.stringify(result))
|