My goal is to organize the pages in my database in a hierarchical "tree" view. Each page has a unique ID and a parent property that indicates which page it is a child of.
I am looking for an efficient way to recursively nest these objects so that each child page is nested within its appropriate parent page based on the parent ID reference. Here is the initial array:
[
{
_id: 1,
title: 'Page A-1',
parent: null
},
{
_id: 2,
title: 'Page A-2',
parent: 1
},
{
_id: 3,
title: 'Page A-3',
parent: 2
},
{
_id: 4,
title: 'Page A-4',
parent: 3
},
{
_id: 5,
title: 'Page A-5',
parent: 4
},
{
_id: 6,
title: 'Page B-1',
parent: null
},
{
_id: 7,
title: 'Page B-2',
parent: 6
},
{
_id: 8,
title: 'Page B-3',
parent: 7
},
{
_id: 9,
title: 'Page B-4',
parent: 8
},
{
_id: 10,
title: 'Page B-5',
parent: 8
},
{
_id: 11,
title: 'Page C-1',
parent: null
}
]
The desired transformed array would look like this:
[
{
_id: 1,
title: 'Page A-1',
children: [
{
_id: 2,
title: 'Page A-2',
children: [
{
_id: 3,
title: 'Page A-3',
children: [
{
_id: 4,
title: 'Page A-4',
children: [
{
_id: 5,
title: 'Page A-5',
children: [
]
}
]
}
]
}
]
}
]
},
{
_id: 6,
title: 'Page B-1',
children: [
{
_id: 7,
title: 'Page B-2',
children: [
{
_id: 8,
title: 'Page B-3',
children: [
{
_id: 9,
title: 'Page B-4',
children: []
},
{
_id: 10,
title: 'Page B-5',
children: []
}
]
}
]
}
]
},
{
_id: 11,
title: 'Page C-1',
children: []
}
]