Build tree from flat array
function buildTree ( nodes , parentId = null ) {
const tree = [ ] ;
for ( const node of nodes ) {
if ( node . parentId === parentId ) {
const children = buildTree ( nodes , node . id ) ;
if ( children . length ) {
node . children = children ;
}
tree . push ( node ) ;
}
}
return tree ;
}
const flatArray = [
{ id : 1 , name : "Node 1" , parentId : null } ,
{ id : 2 , name : "Node 1.1" , parentId : 1 } ,
{ id : 3 , name : "Node 1.1.1" , parentId : 2 } ,
{ id : 4 , name : "Node 4" , parentId : null } ,
{ id : 5 , name : "Node 4.1" , parentId : 4 } ,
{ id : 6 , name : "Node 4.1.1" , parentId : 5 } ,
] ;
const tree = buildTree ( flatList ) ;
console . log ( JSON . stringify ( tree , null , 2 ) ) ;
[
{
"id" : 1 ,
"name" : "Node 1" ,
"parentId" : null ,
"children" : [
{
"id" : 2 ,
"name" : "Node 1.1" ,
"parentId" : 1 ,
"children" : [
{
"id" : 3 ,
"name" : "Node 1.1.1" ,
"parentId" : 2
}
]
}
]
} ,
{
"id" : 4 ,
"name" : "Node 4" ,
"parentId" : null ,
"children" : [
{
"id" : 5 ,
"name" : "Node 4.1" ,
"parentId" : 4 ,
"children" : [
{
"id" : 6 ,
"name" : "Node 4.1.1" ,
"parentId" : 5
}
]
}
]
}
]