js实现解析树形结构数据

  • Post author:
  • Post category:其他


js实现解析树形结构数据

这里没有使用递归也是可以实现树形结构解析,使用双循环的方式解析更加快捷。

/**
 * 树形数据解析
 * @param list 数据列表
 * @param config 选项配置(id,pid,children)
 */
export function parseTree(list, config) {
  const id = config?.id || 'id', pid = config?.pid || 'pid', children = config?.children || 'children'
  const treeList = new Array()
  if (!list?.length) return []
  list.forEach(node1 => {
    let isChild = false
    for (const i in list) {
      const node2 = list[i]
      if (node1[pid] && node1[pid] === node2[id]) {
        isChild = true
        if (node2[children]?.length) {
          node2[children].push(node1)
        } else {
          node2[children] = [node1]
        }
        break
      }
    }
    if (!isChild) {
      treeList.push(node1)
    }
  })
  return treeList
}

模拟数据:

export const mockData = [
  { id: 1 },
  { id: 2, pid: 1 },
  { id: 3, pid: 2 },
  { id: 4, pid: 1 },
  { id: 5 },
  { id: 6, pid: 5 },
  { id: 7, pid: 5 }
]

解析结果:

      const treeList = parseTree(mockData)
      console.log(JSON.stringify(treeList))

打印结果:

[{"id":1,"children":[{"id":2,"pid":1,"children":[{"id":3,"pid":2},{"id":3,"pid":2}]},{"id":4,"pid":1},{"id":2,"pid":1,"children":[{"id":3,"pid":2},{"id":3,"pid":2}]},{"id":4,"pid":1}]},
 {"id":5,"children":[{"id":6,"pid":5},{"id":7,"pid":5},{"id":6,"pid":5},{"id":7,"pid":5}]}]



版权声明:本文为qq_34157798原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。