I'm trying to create a tree. But I dont know how replace a item recursively inside a tree.
I have an array of items, each item if is on top parentId is undefined and if has clindren, each children has a parentId property that show how is his parent.
I'm trying to create a method that find that item inside children property, who can have 1 or more levels.
And if its possible return updated array
This is my code:
const onChangeStatusEditable = () => {
const updatedBranch: IBranch = Object.assign({}, branch, {
editable: !editable,
});
let updatedBranchs: Array<IBranch> = [];
if (parentId === undefined) {
const index = branchs.findIndex( (b: IBranch) => b.id === branch.id);
updatedBranchs = Object.assign([], branchs, {
[index]: updatedBranch,
});
onUpdateBranchs(updatedBranchs);
} else {
// EDIT: efforts
I'm tryin with this recursive method
}
};
// EDIT
export const replaceBranch = (branchs: Array<IBranch>, branch: IBranch): Array<IBranch> => {
let updated: Array<IBranch> = [];
branchs.forEach((b: IBranch) => {
if (b.children) {
updated = replaceBranch(b.children, branch);
if (updated) {
return updated;
}
}
if (b.id === branch.id) {
const index: number = branchs.findIndex((c: IBranch) => c.id === branch.id);
b.children[index] = branch;
updated = b.children;
console.log("founded: ", b);
return updated;
}
});
return updated;
};
And IBrach has this interface:
export interface IBranch {
id: number;
parentId: number | undefined;
active: boolean;
favorite: boolean;
title: string;
editable: boolean;
level: number;
checkbox: boolean;
checkboxEnabled: boolean;
children: Array<any>;
}
Data:
[
{
"id":0,
"active":false,
"favorite":false,
"level":0,
"title":"New Branch 0",
"editable":false,
"checkbox":false,
"checkboxEnabled":false,
"children":[
{
"id":1,
"parentId":0,
"active":false,
"favorite":false,
"level":1,
"title":"New Branch 1",
"editable":false,
"checkbox":false,
"checkboxEnabled":false,
"children":[
]
}
]
}
]