Iterate nested array of JSON objects and append children to a particular object using jQuery/React
We are trying to create a tree view navigation using PnP react TreeView control for SharePoint document library using SPFx web part. We are are getting and setting initial data to the component's state by making an REST call to get first level folders. Below is the JSON array we are setting to the component state.
TreeLinks: [
{
key: UniqueId,
label: "Training Documents",
data: ServerRelativeUrl
}
{
key: UniqueId,
label: "Training Videos",
data: ServerRelativeUrl
}
{
key: UniqueId,
label: "Training Events",
data: ServerRelativeUrl
}
]
Note: "TreeLinks" is an array of type "ITreeItem" and it is state of the component. We want to add children to a specific node on select/click event. Suppose we clicked on "Training Documents" and it's sub folders are "SharePoint, PowerApps, Power Automate, Power BI, SQL"
Expected output.
TreeLinks: [
{
key: UniqueId,
label: "Training Documents",
data: ServerRelativeUrl,
children: [
{
key: UniqueId,
label: "SharePoint",
data: ServerRelativeUrl
}
{
key: UniqueId,
label: "PowerApps",
data: ServerRelativeUrl
}
{
key: UniqueId,
label: "Power Automate",
data: ServerRelativeUrl
}
{
key: UniqueId,
label: "Power BI",
data: ServerRelativeUrl
}
{
key: UniqueId,
label: "SQL",
data: ServerRelativeUrl
}
]
}
{
key: UniqueId,
label: "Training Videos",
data: ServerRelativeUrl
}
{
key: UniqueId,
label: "Training Events",
data: ServerRelativeUrl
}
]
and if we click further on "PowerApps" node, expected output
TreeLinks: [
{
key: UniqueId,
label: "Training Documents",
data: ServerRelativeUrl,
children: [
{
key: UniqueId,
label: "SharePoint",
data: ServerRelativeUrl
}
{
key: UniqueId,
label: "PowerApps",
data: ServerRelativeUrl,
children: [
{
key: UniqueId,
label: "Canvas Apps",
data: ServerRelativeUrl
}
{
key: UniqueId,
label: "Model Driven Apps",
data: ServerRelativeUrl
}
{
key: UniqueId,
label: "Portal Apps",
data: ServerRelativeUrl
}
]
}
{
key: UniqueId,
label: "Power Automate",
data: ServerRelativeUrl
}
{
key: UniqueId,
label: "Power BI",
data: ServerRelativeUrl
}
{
key: UniqueId,
label: "SQL",
data: ServerRelativeUrl
}
]
}
{
key: UniqueId,
label: "Training Videos",
data: ServerRelativeUrl
}
{
key: UniqueId,
label: "Training Events",
data: ServerRelativeUrl
}
]
IMPORTANT: Nesting can be upto n number of levels.
Requesting to help us out on adding children to nested array of JSON objects dynamically.
For information about TreeView control please see this link