数组和树的互相转换

85 阅读1分钟

数组和树的互相转换

数组转树

let arr = [
	{ id: 1, name: '部门1', pid: 0 },
	{ id: 2, name: '部门2', pid: 1 },
	{ id: 3, name: '部门3', pid: 1 },
	{ id: 4, name: '部门4', pid: 3 },
	{ id: 5, name: '部门5', pid: 4 },
]

function arrayToTree(items) {
	const result = [] // 存放结果集
	const itemMap = {} //

	// 先转成map存储
	for (const item of items) {
		itemMap[item.id] = { ...item, children: [] }
	}

	for (const item of items) {
		const id = item.id
		const pid = item.pid
		const treeItem = itemMap[id]
		if (pid === 0) {
			result.push(treeItem)
		} else {
			itemMap[pid].children.push(treeItem)
		}
	}
	return result
}

/**
 * 递归查找,获取children
 */

const getChildren = (data, children, pid) => {
	for (const item of data) {
		if (item.pid === pid) {
			const newItem = { ...item, children: [] }
			children.push(newItem)
			getChildren(data, newItem.children, item.id)
		}
	}
}

/**
 * 转换方法
 */
const arrayToTree2 = (data, pid) => {
	const result = []
	getChildren(data, result, pid)
	return result
}

arrayToTree(arr)

arrayToTree2(arr, [], 0)

树转数组

const tree = {
	id: 1,
	name: '部门1',
	pid: 0,
	children: [
		{
			id: 2,
			name: '部门2',
			pid: 1,
			children: [],
		},
		{
			id: 3,
			name: '部门3',
			pid: 1,
			children: [
				{
					id: 4,
					name: '部门4',
					pid: 3,
					children: [
						{
							id: 5,
							name: '部门5',
							pid: 4,
							children: [],
						},
					],
				},
			],
		},
	],
}

function treeToArray(tree) {
	const result = []
	function flatChildren(node) {
		const { id, name, pid } = node
		result.push({ id, name, pid })

		for (let i = 0; i < node.children.length; i++) {
			flatChildren(node.children[i])
		}
	}
	flatChildren(tree)
	return result
}
treeToArray(tree)