如何在 JavaScript 中的子项之间遍历以从 JSON 创建面包屑导航 UI

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

我需要的是根据定义面包屑结构的 JSON 创建面包屑。

Parent / Node >Comm> Forms Code>Test Menu

问题

在嵌套 Json 对象中 parent_id 与 json 对象中的 id 有关。

js代码

        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

欢迎提出任何建议

创建一个由 id 索引的节点字典,然后从叶节点开始跟随 parent_id 并从您在开始时创建的字典中获取父节点。边走边将节点附加到表示面包屑的数组的开头

类似于:

遍历时:

        nodesDictionary[node.id] = {
          node,
          tree_node: total
        };

然后:

    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