前端 递归 数组转树形,树形转数组

本文介绍了如何使用JavaScript通过递归方法将数组转换为树形结构,并演示了从树形结构转换回一维数组的过程,展示了在IT技术中处理数据结构的实用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入代码片
// 数组转树形
let rootList = [{
				id: 1,
				parent: null,
				text: '菜单1'
			},
			{
				id: 2,
				parent: null,
				text: '菜单1'
			},
			{
				id: 11,
				parent: 1,
				text: '菜单1-1'
			},
			{
				id: 12,
				parent: 1,
				text: '菜单1-2'
			},
			{
				id: 21,
				parent: 2,
				text: '菜单2-1'
			},
			{
				id: 23,
				parent: 2,
				text: '菜单2-2'
			},
			{
				id: 33,
				parent: 23,
				text: '菜单3-23'
			},
		]
		// 一维数组转树形,从外向里递归
		function getTreeList(rootList, id, list) {
			for (let s of rootList) {
				if (s.parent == id) {
					list.push(s) // 拿到第一层
				}
			}
			for (let i of list) {
				i.children = getTreeList(rootList, i.id, []); // 添加子集
				if(!i.children.length) delete i.children; // 删除 空 chidren
			}
			return list 
		}
		const res = getTreeList(rootList, null, [])
		console.log(res, '数组转树形')

// 树形转数组
// 树形转一维数组,从里向外递归
		let arrc = [
			{
				id:1,
				parent:null,
				text:'第一',
				children:[
					{
						id: 11,
						parent:1,
						text:'第一yi',
						children:[
							{
								id:12,
								parent:11,
								text:'第一yier',
							}
						],
					}
				],
			},
			{
				id:2,
				parent:null,
				text:'第二',
				children:[
					{
						id:22,
						parent:2,
						text:'第二yi',
						children:[
							{
								id:32,
								parent:22,
								text:'第二yier'
							}
						]
					}
				]
			}
		]
		function treeArr(arr) {// 拿到外层
			let arrs = []
			for (let s of arr) { 
				if(s.children){ // 判断 子集存在
				arrs.push(...treeArr(s.children)) // 递归自己身上的子集 
				delete s.children // 删除子集
				} 
				arrs.push(s)  // 拿到最里面的子集
			}
			return arrs // 获取数组
		}
		const aff = treeArr(arrc)
        console.log(aff, '树形转一维数组')


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值