csv文件转成树结构

/**
   * 每个csv文件转成一个person对象,然后根据父子关系构建树
   */
  const transferTree = () => {
    interface Person {
      name: string
      age: number
      parent: string | null
      children?: Person[]
    }
    // csv文件转成树结构
    const csv = `
    name,age,parent
    Bob,30,David
    David,60,
    Anna,10,Bob
  `
    const change = (csv: string): Person[] => {
      // 去重根据\n生成二维数组
      const lines = csv
        .trim()
        .split('\n')
        .map(line => line.trim().split(',')) //
      console.log('lines', lines)
      const headers = lines[0]
      const data = lines.slice(1)
      const people: { [name: string]: Person } = {}
      // 将每个人员信息转换成Person对象
      for (const row of data) {
        const person: Person = {
          name: row[0],
          age: Number(row[1]),
          parent: row[2] || null,
          children: [],
        }
        people[person.name] = person
      }
      // 根据父子关系构建成一棵树
      // Object.values()取得值得数组
      for (const person of Object.values(people)) {
        if (person.parent) {
          const parent = people[person.parent]
          parent?.children?.push(person)
        }
      }
      // 返回根节点
      return Object.values(people).filter(person => !person.parent)
    }
    const tree = change(csv)
    console.log(tree)
  }
posted @   zeal666  阅读(79)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
历史上的今天:
2021-03-09 伪类选择器和伪元素选择器的区别
点击右上角即可分享
微信分享提示