Get leaf node depth from tree view in angularJS

2019-06-13 17:21发布

问题:

I have a tree view Json object is

{
  "Name": "Root",
  "Id": "-1",
  "ParentId": "null",
  "children": [
    {
      "Name": "Math",
      "Id": "1",
      "ParentId": "-1",
      "children": [
        {
          "Name": "Addition",
          "Id": "3",
          "ParentId": "1",
          "children": [
            {
              "Name": "Two Numbers",
              "Id": "5",
              "ParentId": "3",
              "children": []
            },
            {
              "Name": "Three Numbers",
              "Id": "6",
              "ParentId": "3",
              "children": []
            }
          ]
        },
        {
          "Name": "Substraction",
          "Id": "4",
          "ParentId": "1",
          "children": [
            {
              "Name": "Four Numbers",
              "Id": "7",
              "ParentId": "4",
              "children": []
            },
            {
              "Name": "Five Numbers",
              "Id": "8",
              "ParentId": "4",
              "children": []
            }
          ]
        }
      ]
    },
    {
      "Name": "English",
      "Id": "1",
      "ParentId": "-1",
      "children": []
    }
  ],
  "selected": "selected"
}

If i select "Two numbers" leaf node, mytree.currentNode.Name only shows "Two Numbers", But i want to display from the depth of the leaf node. "Root / Math / Addition / Two Numbers" Is there any way to display?
Please help me. Thanks in advance

回答1:

It's the design descision that you took is making it hard for you to get the entire depth.

There is two ways of storing hierarchical data. Either use reference or use ID. Do not mix and match.

Instead of ParentId, if you keep the reference of parent, then you would be very easily able to walk down entire tree.

If you want to use parent ID, then instead of nested children use a dictionary of ID and object. In that way also you could very easily (and fast) traverse the tree