Skip to content

数组转树

js
const arr = [
	{ id: 1, pid: null },
	{ id: 2, pid: 1 },
	{ id: 3, pid: 2 },
	{ id: 4, pid: 1 },
	{ id: 5, pid: 4 },
]

将上面的数组转换为下面的树形结构

js
{
  "id": 1,
  "pid": null,
  "children": [
    {
      "id": 2,
      "pid": 1,
      "children": [
        {
          "id": 3,
          "pid": 2,
          "children": []
        }
      ]
    },
    {
      "id": 4,
      "pid": 1,
      "children": [
        {
          "id": 5,
          "pid": 4,
          "children": []
        }
      ]
    }
  ]
}

map缓存所有节点 遍历map恢复

js
function convert(list, rootId) {
	const result = []

	const listMap = list.reduce((pre, cur) => {
		pre[cur.id] = cur
		return pre
	}, {})

	Object.keys(listMap).forEach((key) => {
		const item = listMap[key]

		if (item.id === rootId) {
			// 根
			result.push(item)
		} else {
			// 子节点
			const parent = listMap[item.pid]
			if (parent) {
				parent.children = parent.children || []
				parent.children.push(item)
			}
		}
	})

	return result[0] || {}
}

const result = convert(arr, 1)
console.log(JSON.stringify(result, null, 4))