Issue
What I need is to create a breadcrumb from a JSON defining the structure of the breadcrumb.
Parent / Node >Comm> Forms Code>Test Menu
Problem
In Nested Json object parent_id is related to id in json object.
Js code
ngOnInit() {
let data = [];
let jsonValues = JSON.stringify(this.jasonData1);
const main_menu_items = JSON.parse(jsonValues);
var treeNodes = [];
this.childernNodes = nestedChildrens(main_menu_items.value, 0);
console.log(this.childernNodes);
function nestedChildrens(nodes, level) {
//treeNodes[level] = treeNodes[level] || [];
var total = 0;
nodes.children.forEach(node => {
var ccount = 0;
if ("children" in node) {
var ccount = nestedChildrens(node, total + 1);
} else {
ccount = 1;
}
// console.log(node.parent_id);
treeNodes.push({
node,
tree_node: total
});
total += ccount;
});
const sorted = Object.values(treeNodes).sort(
(a, b) => a.node.id - b.node.id
);
return sorted;
}
}
}
Stackblitz
https://stackblitz.com/edit/angular-tree-node-test-znreuv
Any suggestion is most welcome
Solution
Create a dictionary of nodes indexed by id, then starting at the leaf node follow the parent_id's and get the parent nodes from the dictionary you created in the beginning. As you go, append the nodes to the beginning of an array representing the breadcrumb.
Something like:
While traversing:
nodesDictionary[node.id] = {
node,
tree_node: total
};
Then:
let currentNode = nodesDictionary["156"];
while (currentNode && currentNode.node.parent_id) {
this.childernNodes = [currentNode, ...this.childernNodes];
currentNode = nodesDictionary[currentNode.node.parent_id];
}
https://stackblitz.com/edit/angular-tree-node-test-hphtlw?file=src/app/app.component.ts
Answered By - Tiago Coelho
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.