I am struggling with a recursive data structure similar to the example provided below. My goal is for each branch, starting from null (parentTagId), to extend as far as the final one.
I have no clue on how to achieve this, so any suggestions would be greatly appreciated!
Original data:
[
{ TagId: 2, ParentTagId: null, Name: 'women' },
{ TagId: 5, ParentTagId: 2, Name: 'bottom' },
{ TagId: 4, ParentTagId: 2, Name: 'top' },
{ TagId: 7, ParentTagId: 4, Name: 'shirt' },
{ TagId: 8, ParentTagId: 4, Name: 'tshirt' },
{ TagId: 12, ParentTagId: 7, Name: 'longsleeve' },
{ TagId: 16, ParentTagId: null, Name: 'men' }
]
Expected outcome:
women > bottom
women > top > shirt > longsleeve
women > tshirt
men
Output data:
[
{
path: [
{ TagId: 2, ParentTagId: null, Name: 'women' },
{ TagId: 5, ParentTagId: 2, Name: 'bottom' }
]
},
{
path: [
{ TagId: 2, ParentTagId: null, Name: 'women' },
{ TagId: 4, ParentTagId: 2, Name: 'top' },
{ TagId: 7, ParentTagId: 4, Name: 'shirt' },
{ TagId: 12, ParentTagId: 7, Name: 'longsleeve' }
]
},
{
path: [
{ TagId: 2, ParentTagId: null, Name: 'women' },
{ TagId: 4, ParentTagId: 2, Name: 'top' },
{ TagId: 8, ParentTagId: 4, Name: 'tshirt' }
]
},
{
path: [
{ TagId: 16, ParentTagId: null, Name: 'men' }
]
}
]