代码
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));