I have a hierarchy of nodes in a checkbox tree and I would like to know how to make a recursive function that returns its complete path from each final element of a node, depending on whether it is selected or not.
Can someone help me?
Data Example:
const data = {
id: 22,
selected: true,
children: [
{
id: 4813,
children: [],
selected: true,
},
{
id: 4720,
selected: true,
children: [
{
id: 4838,
selected: true,
children: [],
},
{
id: 4839,
selected: true,
children: [],
},
{
id: 4840,
selected: true,
children: [],
},
{
id: 4841,
selected: true,
children: [],
}
],
},
{
id: 4719,
selected: true,
children: [
{
id: 4272,
selected: true,
children: [
{
id: 4273,
selected: true,
children: [],
},
{
id: 4275,
selected: false,
children: [],
},
{
id: 4276,
selected: true,
children: [],
},
{
id: 4277,
selected: false,
children: [],
},
{
id: 4278,
selected: true,
children: [],
},
{
id: 4279,
selected: false,
children: [],
},
],
},
],
},
],
};
response = [
"22/4813",
"22/4720/4838",
"22/4720/4839",
"22/4720/4840",
"22/4720/4841",
"22/4719/4272/4273",
"22/4719/4272/4276",
"22/4719/4272/4278"
];
Here is my code:
export const getHierarchyNodes = (hierarchy: any) => {
let idNodes: Array<string> = [];
const clonedHierarchy = { ...hierarchy };
// const parentId: number = clonedHierarchy.id;
// const parentChildren: any = [];
clonedHierarchy.children.forEach((child: any) => {
if (child.selected || child.checked) {
// const childNode: string = `${parentId}`;
const descendetsNodes = getDescendetsNodes(child);
console.log("descendents: ", descendetsNodes);
}
});
return idNodes;
};
const getDescendetsNodes = (node: any) => {
let descendents: any = [];
const dmaExtractor = (items: any) => {
items.forEach((child: any) => {
if (child.selected || child.checked) {
descendents.push(child);
}
if (Array.isArray(child.children)) {
dmaExtractor(child.children);
}
});
};
if (Array.isArray(node.children)) {
descendents.push(node);
dmaExtractor(node.children);
}
console.log("descendents: ", descendents);
return descendents;
};