Here is an object that I am working with:
{
"name": "A",
"children": [
{
"name": "B",
"open": false,
"registry": true,
"children": [
{
"name": "C",
"children": [
{
"name": "D",
"children": []
}
]
},
{
"name": "E",
"registry": true
}
]
}
]
}
I am trying to simplify this tree structure and extract only the nodes where registry
is set to true.
First, I attempted to locate all these nodes:
public nodesRegistry = new Map();
findRegistryNodes(node: TreeNode) {
if (!node) return;
if (node?.registry) {
this.nodesRegistry.set(node, node);
}
if (node.children)
node.children.forEach((node: TreeNode) => {
this.findRegistryNodes(node);
});
}
Next, I need to reconstruct the tree:
const parents = this.getParentNodeRegistry();
const children = this.getChildrenNodeRegistry(parents);
This method identifies all parent nodes for the discovered children:
getParentNodeRegistry() {
const nodesWithRegistry = new Map<string, TreeNode>();
for (const node of this.nodesRegistry.keys()) {
let parent = node.parent;
do {
if (parent.parent && !parent.parent.parent) {
nodesWithRegistry.set(parent.name, parent);
break;
}
parent = parent.parent;
} while (parent);
}
return nodesWithRegistry;
}
Then, we collect all children nodes:
getChildrenNodeRegistry(nodes: Map<string, TreeNode>) {
return Array.from(nodes.values()).reduce((children, node) => {
this.reduceNodesWithRegistrer(node);
return (children = children.concat(node));
}, []);
}
The resulting nodes still contain elements without the registry: true
property. How can this be resolved?