I have an array of objects like this
const ticketsData = [
{ id: 1, title: 'parent', parent: 0, url: '' },
{ id: 2, title: 'parent', parent: 0, url: '' },
{ id: 3, title: 'child', parent: 1, url: '' },
{ id: 4, title: 'sub child', parent: 3, url: '' },
{ id: 5, title: 'sub sub child', parent: 4, url: '' },
{ id: 6, title: 'sub sub sub child', parent: 5, url: '' },
{ id: 10, title: 'sub sub child 2', parent: 4, url: '' },
{ id: 13, title: 'sub child 2', parent: 3, url: '' },
{ id: 14, title: 'child', parent: 2, url: '' },
{ id: 7, title: 'sub sub sub child', parent: 5, url: '' },
{ id: 8, title: 'sub sub sub child', parent: 5, url: '' },
{ id: 9, title: 'sub sub sub child', parent: 5, url: '' },
{ id: 11, title: 'sub sub child 3', parent: 4, url: '' },
{ id: 12, title: 'sub sub child 4', parent: 4, url: '' }
];
and I want to create a nested array of object upto a limit, say 10. So when the count reduces to zero it should return the array till that child/parent.
> This is my expected Output:
[{ id: 1, title: 'parent', parent: 0, url: '', children: [
{ id: 3, title: 'child', parent: 1, url: '', children:[
{ id: 4, title: 'sub child', parent: 3, url: '', children:[
{ id: 5, title: 'sub sub child', parent: 4, url: '' , children:[
{ id: 6, title: 'sub sub sub child', parent: 5, url: '', children:[] },
{ id: 7, title: 'sub sub sub child', parent: 5, url: '', children:[] },
{ id: 8, title: 'sub sub sub child', parent: 5, url: '', children:[] },
{ id: 9, title: 'sub sub sub child', parent: 5, url: '', children:[] }
]},
{ id: 10, title: 'sub sub child 2', parent: 4, url: '', children:[] },
{ id: 11, title: 'sub sub child 3', parent: 4, url: '', children:[] }
] }
] }
] }]
I tried this but getting all the objects in separate array.
const createTicketTree = (tickets, count) => {
let ticketObj = {};
let ticketHierarchy = []
tickets.map( ticket => {
ticketObj[ticket.id] = { ...ticket, children: [] };
if(ticket.parent && count && count--) {
ticketObj[ticket.parent].children.push(ticketObj[ticket.id])
}
else {
ticketHierarchy.push(ticketObj[ticket.id])
}
});
return ticketHierarchy;
};
This is how I am calling the function to get the nested parent-children relation upto 10. Is there any lodash/underscore implementation to acheive this? Any help would be appreciated
createTicketTree(ticketsData, 10);