Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

How to Traverse between children in JavaScript to create breadcrumb UI from JSON

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

>A>B>Comm>comm Code>Forms Code>Test Menu

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 disctionary 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...