首页 > 其他分享 >数组数据转为树状结构

数组数据转为树状结构

时间:2022-11-09 15:37:29浏览次数:45  
标签:arr parent 树状 children let 数组 null 转为 id

代码

let arr = [
      { id: 3, parent: 2 },
      { id: 1, parent: null },
      { id: 2, parent: 1 },
    ]

let root= arr.map(i=>{
	let children = arr.filter(j=>j.parent==i.id)
	if(children.length){
		i.children=children
	}
	return i
}).find(item=>item.parent==null)

console.log(JSON.stringify(root,null,2));

结果:

image

标签:arr,parent,树状,children,let,数组,null,转为,id
From: https://www.cnblogs.com/grblog/p/16873881.html

相关文章