Seeking assistance with converting this JSON tree nodes into the final JSON structure by recursively joining the nodes. Any help would be greatly appreciated. I require a recursive function in JavaScript. Provided below is the sample input and the desired output. Input
{
root: {
parent_id: 'root',
current_id: 'root',
children: ['node_233443'],
type: 'stack',
},
node_233443: {
parent_id: 'root',
current_id: 'node_233443',
children: ['node_fdfd33', 'node_hd44d4'],
type: 'column',
},
node_fdfd33: {
parent_id: 'node_233443',
current_id: 'node_fdfd33',
children: [],
type: 'text',
},
node_hd44d4: {
parent_id: 'node_233443',
current_id: 'node_hd44d4',
children: [],
type: 'image',
},
};
Desired Output
{
parent_id: 'root',
current_id: 'root',
children: [{
parent_id: 'root',
current_id: 'node_233443',
children: [{
parent_id: 'node_233443',
current_id: 'node_fdfd33',
children: [],
type: 'text',
},
{
parent_id: 'node_233443',
current_id: 'node_hd44d4',
children: [],
type: 'image',
}],
type: 'column',
}],
type: 'stack',
}
This is the solution I have come up with.
const clonedNodes = structuredClone(nodes);
const recurse = (json) => {
json.children = json.children.map((item) => {
if(clonedNodes[item]) {
return recurse(clonedNodes[item])
}
}, [])
return json;
}
console.log(recurse(clonedNodes.root), nodes)
If you have any suggestions for improvement, please share them. Thank you.