js扁平数据转树形数据

69B80F2D-1E00-4FD0-B3B2-136A283B3FAA

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
	<script type="text/javascript">
		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 res = []
	const obj = {}

	for (var i = 0; i < items.length; i++) {
		const id = items[i].id
		const pid = items[i].pid

		obj[id] = {
			...items[i],
			children: []
		}

		const item = obj[id]

		if (items[i].pid === 0) {
			res.push(item)
		} else {
			obj[pid].children.push(item)
		}
	}
	return res
}
console.log(arrayToTree(arr))
	</script>
</body>
</html>
© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片快捷回复

    暂无评论内容