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 @ 2023-03-09 13:45  zeal666  阅读(113)  评论(0)    收藏  举报