0

I am creating a treeview UI from the below Json, I have added the properties node-id, parentId to capture the current expanded structure

I am planning to add a breadcrumb UI component from the selected tree structure.

var tree = [
{ name:"Insights", nodeId :"tree-node-0"},
{ name:"Level1", nodeId :"tree-node-1", parentId: "tree-node-0"},
{ name:"Level2", nodeId :"tree-node-2", parentId:"tree-node-1"},
{ name:"Details", nodeId :"tree-node-10"},
{ name:"SubDetails", nodeId :"tree-node-11", parentId:"tree-node-10"},
{ name:"Summary", nodeId :"tree-node-12", parentId:"tree-node-11"},

];

Below is the tree

Insights
    |
    |---Level1
        |
        |--Level2
Details
    |
    |--SubDetails
        |
        |--Summary

If the user selectes Summary then i want to create a breadCrumb which display links like Details-->SubDetails-->Summary . I am assuming to populate the selected structure nodes into an array and then it would be easy to populate breadcrumb from the array.

If the user selects Summary then from the selected node parentId i want to traverse through the JSON array and find the path.

Need help in above logic

user804401
  • 1,990
  • 9
  • 38
  • 71

1 Answers1

0

var tree = [{
    name: "Insights",
    nodeId: "tree-node-0"
  }, {
    name: "Level1",
    nodeId: "tree-node-1",
    parentId: "tree-node-0"
  }, {
    name: "Level2",
    nodeId: "tree-node-2",
    parentId: "tree-node-1"
  }, {
    name: "Details",
    nodeId: "tree-node-10"
  }, {
    name: "SubDetails",
    nodeId: "tree-node-11",
    parentId: "tree-node-10"
  }, {
    name: "Summary",
    nodeId: "tree-node-12",
    parentId: "tree-node-11"
  },

];

function test(Name, testData) {
  var testData = testData || [];
  var node = tree.find(function(item) {
    return item.name == Name;
  });
  if (node) {
    testData.push(node.name);
    var parent = tree.find(function(item) {
      return item.nodeId == node.parentId;
    });
    if (parent) {
      return test(parent.name, testData);
    } else {
      return testData;
    }

  } else {
    return testData;
  }
}

console.log(test('Summary'));

i added it to display in console , you can check in console

Updated the code

LazyDeveloper
  • 599
  • 3
  • 8