I'm trying to create a tree component. But I dont know how insert a item recursively inside a tree.
Each item its created dinamically and I would like instert/create an item/branch of the tree in each level. Problem is that when I cant insert items on level 3.
For example, I have this code generated:
[{
"id": 0,
"active": false,
"favorite": false,
"level": 0,
"title": "New Branch 0",
"editable": false,
"checkbox": false,
"checkboxEnabled": false,
"children": []
}, {
"id": 1,
"active": false,
"favorite": false,
"level": 0,
"title": "New Branch 1",
"editable": false,
"checkbox": false,
"checkboxEnabled": false,
"children": [{
"id": 3,
"parentId": 1,
"active": false,
"favorite": false,
"level": 1,
"title": "New Branch 3",
"editable": false,
"checkbox": false,
"checkboxEnabled": false,
"children": []
}, {
"id": 4,
"parentId": 1,
"active": false,
"favorite": false,
"level": 1,
"title": "New Branch 4",
"editable": false,
"checkbox": false,
"checkboxEnabled": false,
"children": []
}]
}, {
"id": 2,
"active": false,
"favorite": false,
"level": 0,
"title": "New Branch 2",
"editable": false,
"checkbox": false,
"checkboxEnabled": false,
"children": []
}]
And I'm trying to create a method that insert, for example inside children of New Branch 4 or his children. And that return updated array.
This is my code:
const onCreateChildren = () => {
let newBranch: IBranch = generateBranch(numBranchs);
newBranch = Object.assign({}, newBranch, {
level: level + 1,
parentId: branch.id,
});
let copyChildren: Array<IBranch> = children.slice();
copyChildren.push(newBranch);
const updatedBranch: IBranch = Object.assign({}, branch, {
children: copyChildren,
});
if (parentId === undefined) {
const index: number = branchs.findIndex( (b: IBranch) => b.id === branch.id);
const updatedBranchs: Array<IBranch> = Object.assign([], branchs, {
[index]: updatedBranch,
});
onUpdateBranchs(updatedBranchs);
} else {
const updatedBranchs: any = addBranchInTree(branchs, newBranch);
onUpdateBranchs(updatedBranchs);
}
onUpdateNumBranchs(numBranchs+1);
};
Why doenst work always?? Can someone help me?? Other ideas??
export const addBranchInTree = (branchs: any, branch: IBranch): any => {
return Array.isArray(branchs)
? branchs.map((o: IBranch) => addBranchInTree(o, branch))
: findNode(branchs, branch);
};
const findNode = (branchs: any, branch: any): any => {
if (branchs.children.length > 0) {
branchs.children.forEach((child: any) => {
return findNode(child, branch);
});
}
if (!Array.isArray(branchs)) {
if (branchs.parentId === branch.parentId - 1) {
return branchs.children.push(branch);
}
}
return branchs;
};