Given the following data set, I need to change the value of the leaf property to true of the last nested element.
const data = [
{
label: "root",
data: 1,
expandedIcon: "pi pi-folder-open",
collapsedIcon: "pi pi-folder",
expanded: true,
children: [
{
label: "Italy",
data: 6,
expandedIcon: "pi pi-folder-open",
collapsedIcon: "pi pi-folder",
expanded: true,
children: [
{
label: "Bolognia",
data: 8,
expandedIcon: "pi pi-folder-open",
collapsedIcon: "pi pi-folder",
expanded: true,
children: [],
leaf: false, // <-- this need to be true
},
],
leaf: false,
},
],
leaf: false,
},
];
In this case the target is the object
{
label: "Bolognia",
data: 8,
expandedIcon: "pi pi-folder-open",
collapsedIcon: "pi pi-folder",
expanded: true,
children: [],
leaf: false,
},
This tree will always have this structure, it can be extended or contracted indefinitely.
Having described the above, the expected result is the following
const data = [
{
label: "root",
data: 1,
expandedIcon: "pi pi-folder-open",
collapsedIcon: "pi pi-folder",
expanded: true,
children: [
{
label: "Italy",
data: 6,
expandedIcon: "pi pi-folder-open",
collapsedIcon: "pi pi-folder",
expanded: true,
children: [
{
label: "Bolognia",
data: 8,
expandedIcon: "pi pi-folder-open",
collapsedIcon: "pi pi-folder",
expanded: true,
children: [],
leaf: true, // <-- updated
},
],
leaf: false,
},
],
leaf: false,
},
];
I understand it can be achieved using recursion but I can’t identify how to do it. Thank you for your advices
update 1
I am trying the following to get the target node but I always get undefined
function tried(data) {
if (data.children.length === 0) {
return data;
}
tried(data.children[0]);
}
const output = tried(data[0]);
console.log(output);
>Solution :
You are going the right way, just missing the return on recursion call
const data = [
{
label: 'root',
data: 1,
expandedIcon: 'pi pi-folder-open',
collapsedIcon: 'pi pi-folder',
expanded: true,
children: [
{
label: 'Italy',
data: 6,
expandedIcon: 'pi pi-folder-open',
collapsedIcon: 'pi pi-folder',
expanded: true,
children: [
{
label: 'Bolognia',
data: 8,
expandedIcon: 'pi pi-folder-open',
collapsedIcon: 'pi pi-folder',
expanded: true,
children: [],
leaf: false,
},
],
leaf: false,
},
],
leaf: false,
},
];
const getLastNestedElement = (data) => {
if (data.children.length === 0) {
return data;
}
return getLastNestedElement(data.children[0]); // you need to return
};
const lastNestedElement = getLastNestedElement(data[0]);
lastNestedElement.leaf = true;
console.log(JSON.stringify(lastNestedElement, null, 2));
console.log(JSON.stringify(data, null, 2));