Looking to restructure an array of linked objects into a single tree object sorted by ID. Since the depth is unknown, considering recursion for efficiency. What's the best approach?
The initial array:
const arrObj = [
{
"id": 1,
"children": [
{
"id": 2
},
{
"id": 3
}
]
},
{
"id": 2,
"children": [
{
"id": 4
},
{
"id": 5
}
]
},
{
"id": 3,
"children": [
{
"id": 6
}
]
},
{
"id": 4
}
]
The desired tree structure:
const treeObj = {
"id": 1,
"children": [
{
"id": 2,
"children": [
{
"id": 4
},
{
"id": 5
}
]
},
{
"id": 3,
"children": [
{
"id": 6
}
]
}
]
}
Other properties are present in each object.