Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...