I need help to convert this json tree nodes to final json structure joining the nodes recursively. Any help is appreciated. I need a recursively function in javascript. Given below the sample input and output I needed. My 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',
},
};
My Needed 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 got.
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)
Any help to improve it please.
You could map the
childrenarrays to the objects that correspond to the identifiers in those arrays. You may want to first clone your original object so it does not get mutated: