I'm on a mission to transform a flat JSON object into a nested tree using JavaScript. The unique challenge I'm facing is the need to match one child node to multiple parent nodes, a scenario I haven't found in existing solutions.
Behold, my flat JSON object:
[{
id: 200,
title: "child with 2 parents",
parent_ids: [1, 2]
}, {
id: 202,
title: "child with 1 parent",
parent_ids: [1]
}, {
id: 1,
title: "parent 1",
children: []
}, {
id: 2,
title: "parent 2",
children: []
}]
I'm aware I could potentially loop through parents and children separately to pair them up, but that approach seems inefficient. I'm curious to explore if there's a more efficient method to achieve this.
Here's the desired outcome:
Observe how the child with 2 parents is linked to both parents seamlessly.
[
{
id: 1,
title: "parent 1",
children: [{
id: 200,
title: "child with 2 parents",
parent_ids: [1, 2]
}, {
id: 202,
title: "child with 1 parent",
parent_ids: [1]
}]
},
{
id: 2,
title: "parent 2",
children: [{
id: 200,
title: "child with 2 parents",
parent_ids: [1, 2]
}]
}
]