Skip to content

关系型数组转换成树形结构对象

text
obj = [
  { "id": 3, "parent": 2 },
  { "id": 1, "parent": null },
  { "id": 2, "parent": 1 }
]
// 输出:
o = {
  "obj": {
    "id": 1,
    "parent": null,
    "children": [{
      "id": 2,
      "parent": 1,
      "children": [{
        "id": 3,
        "parent": 2
      }]
    }]
  }
}

实现如下

JavaScript
class Transform {
  constructor(list) {
    this.list = list
    this.head = null
    this.hashMap = new Map()
    this.parse()
  }
  parse() {
    const { list, hashMap } = this
    for (const node of list) {
      const { parent } = node
      if (!parent) {
        this.head = node
      } else {
        const arr = hashMap.has(parent) ? hashMap.get(parent) : []
        arr.push(node)
        hashMap.set(parent, arr)
      }
    }
  }
  toTreeNode() {
    const {
      head: { id },
      hashMap,
    } = this
    const transNode = (node, parent) => {
      const id = node.id
      const children = []
      if (hashMap.has(id)) {
        for (const child of hashMap.get(id)) {
          children.push(transNode(child, id))
        }
      }
      return { id, parent, children }
    }
    const obj = {
      id,
      parent: null,
      children: hashMap.get(id).map(node => transNode(node, id)),
    }
    return { obj }
  }
}

// 使用
const toTree = [
  { id: 3, parent: 2 },
  { id: 1, parent: null },
  { id: 2, parent: 1 },
]
const toTreeParse = new Transform(toTree)
const result = toTreeParse.toTreeNode()
console.log(result)