Skip to content

arrayToTree - 扁平数组转换为树状结构


将扁平数组转换为树状结构。

参数

  • data: Array - 原始数据数组

  • options: Object - 配置选项

  • id: string - 唯一标识字段名,默认'id'

  • pid: string - 父级标识字段名,默认'pid'

  • children: string - 子级字段名,默认'children'

返回值

  • Array - 处理后的树状结构数据

使用示例

javascript
const data = [
  { id: 1, name: '父级1', pid: 0 },

  { id: 2, name: '子级1', pid: 1 },

  { id: 3, name: '子级2', pid: 1 }
]

const tree = arrayToTree(data)

源码

源码
js
/**
 * 处理树状数据的工具函数
 * @param {Array} data - 原始数据数组
 * @param {Object} options - 配置选项
 * @param {string} [options.id='id'] - 唯一标识字段名
 * @param {string} [options.pid='pid'] - 父级标识字段名
 * @param {string} [options.children='children'] - 子级字段名
 * @returns {Array} 处理后的树状结构数据
 *
 * @example
 * const data = [
 *   { id: 1, name: '父级1', pid: 0 },
 *   { id: 2, name: '子级1', pid: 1 },
 *   { id: 3, name: '子级2', pid: 1 }
 * ]
 * const tree = arrayToTree(data)
 */
function arrayToTree(data = [], options = {}) {
  const { id = 'id', pid = 'pid', children = 'children' } = options

  const tree = []
  const map = {}

  // 将数据存入哈希表
  data.forEach(item => {
    map[item[id]] = {
      ...item,
      [children]: []
    }
  })

  // 构建树状结构
  data.forEach(item => {
    const node = map[item[id]]
    if (item[pid] === 0 || !map[item[pid]]) {
      // 根节点
      tree.push(node)
    } else {
      // 子节点
      map[item[pid]][children].push(node)
    }
  })

  // 清理空的children数组
  const clearEmptyChildren = nodes => {
    nodes.forEach(node => {
      if (node[children].length === 0) {
        delete node[children]
      } else {
        clearEmptyChildren(node[children])
      }
    })
  }
  clearEmptyChildren(tree)

  return tree
}

Released under the MIT License.