扁平化数组和树结构相互转换(递归方式)

扁平化数组转为树

function buildTree(data,pid){
	const tree = [];
	for(const item of data){
		if(item.pid == pid){
			const children = buildTree(data,item.id);
			if(children.length > 0)item.children = children;
			tree.push(item)
		}
		
	}
	return tree;
}
const data = [
	{id:1,name:'1',pid:0,type:1},
	{id:2,name:'1-1',pid:1,type:1},
	{id:3,name:'3',pid:0,type:1},
	{id:4,name:'3-1',pid:3,type:1},
	{id:5,name:'1-1-1',pid:2,type:2},
	{id:6,name:'3-1-1',pid:4,type:1},
	{id:7,name:'3-1-2',pid:3,type:2},
	{id:8,name:'3-1-3',pid:3,type:2},
]

const tree = buildTree(data,0)
console.log(JSON.stringify(tree))

树状结构拆分为扁平

const json = [{"id":1,"name":"1","pid":0,"type":1,"children":[{"id":2,"name":"1-1","pid":1,"type":1,"children":[{"id":5,"name":"1-1-1","pid":2,"type":2}]}]},{"id":3,"name":"3","pid":0,"type":1,"children":[{"id":4,"name":"3-1","pid":3,"type":1,"children":[{"id":6,"name":"3-1-1","pid":4,"type":1}]},{"id":7,"name":"3-1-2","pid":3,"type":2},{"id":8,"name":"3-1-3","pid":3,"type":2}]}];

const arr = []
function splitTree(data){
	for(const item of data){
		if(item.children?.length > 0){
			splitTree(item.children)
			delete item.children
		}
		arr.push(item)
	}
}
splitTree(json)
console.log(arr)

去除树状数据中特定的节点

const json = [{"id":1,"name":"1","pid":0,"type":1,"children":[{"id":2,"name":"1-1","pid":1,"type":1,"children":[{"id":5,"name":"1-1-1","pid":2,"type":2}]}]},{"id":3,"name":"3","pid":0,"type":1,"children":[{"id":4,"name":"3-1","pid":3,"type":1,"children":[{"id":6,"name":"3-1-1","pid":4,"type":1}]},{"id":7,"name":"3-1-2","pid":3,"type":2},{"id":8,"name":"3-1-3","pid":3,"type":2}]}];

function deleteNodesByType(data){
	for(let i=data.length-1;i>=0;i--){
		let item = data[i];
		if(item.type === 2){
			data.splice(i,1)
		}else if(item.children?.length>0){
			deleteNodesByType(item.children)
		}
	}
}
deleteNodesByType(json)
console.log(JSON.stringify(json))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值