0
点赞
收藏
分享

微信扫一扫

【工具方法】路径枚举构建树形结构

陆公子521 2022-04-25 阅读 50
javascript

目的

实现类似于 RedisDesktopManager 中键名的 : 展示为树形结构的功能。

参考

  • 路径字符串数据转化为树型层级对象,path to json tree

实现

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))

在这里插入图片描述

举报

相关推荐

0 条评论