I'm trying to create a tree component. But I dont know how remove a item recursively inside a tree.
Each item its created dinamically and I would like remove an item/branch of the tree in each level.
The problem is that when I select and item and has not children I have to find his parent and remove selected item. But If selected item has children, I have to find his parent, get all children of selected item, update all parentId of children, added to parent and remove selected item. Do all of that recursively and return updated array.
const data = [
{id: 1, title: 'foo', children: [
{id: 11, parentId: 1, title: 'bar',},
{id: 12, parentId: 1, title: 'baz', children: [
{id: 121, parentId: 12, title: 'qux'},
{id: 122, parentId: 12, title: 'quz'}
]},
{id: 13, parentId: 1, title: 'corge'}
]},
{id: 2, title: 'grault'}
];
const id = 12;
console.log (removeElement(data, id));
Result should be:
const data = [
{id: 1, title: 'foo', children: [
{id: 11, parentId: 1, title: 'bar', children: [
{id: 121, parentId: 11, title: 'qux'},
{id: 122, parentId: 11, title: 'quz'}
]},
{id: 13, parentId: 1, title: 'corge'}
]},
{id: 2, title: 'grault'}
];
See Question&Answers more detail:os