Skip to content Skip to sidebar Skip to footer

Find All The Parents Of Each Element

I'm trying to create a breadcrumb without using the url (the route provider) and without using jQuery. I have a tree like that Humans Trees Animals Cats Lions Dogs

Solution 1:

You are iterating over the tree, but it won't help if you don't keep some information. The simplest solution to your problem is to build an index of all nodes that points to their parents.

This code will work if roleName has unique values across the whole tree:

var tree = [
    { "roleName" : "Humans", "roleId" : "role2", "children" : []},
    { "roleName" : "Trees", "roleId" : "role2", "children" : []},
    { "roleName" : "Animals", "roleId" : "role2", "children" : [
        { "roleName" : "Cats", "roleId" : "role11", "children" : []},
        { "roleName" : "Lions", "roleId" : "role11", "children" : []},
        { "roleName" : "Dogs", "roleId" : "role11", "children" : [
            { "roleName" : "Terrier", "roleId" : "role11", "children" : []},
            { "roleName" : "Bulldog", "roleId" : "role11", "children" : []},
            { "roleName" : "Cocker", "roleId" : "role11", "children" : []},
        ]}
    ]},
    { "roleName" : "Cars", "roleId" : "role2", "children" : []}
];

var index = {};

functionbuildIndex(root, children) {
    for(var i in children) {
        index[children[i].roleName] = root;
        buildIndex(children[i].roleName, children[i].children);
    }
}

buildIndex("Root", tree);

functiongetPath(leaf) {
    return index[leaf] ? getPath(index[leaf]).concat([leaf]) : [leaf];
}

getPath("Bulldog");// returns ["Root", "Animals", "Dogs", "Bulldog"]

JSFiddle: http://jsfiddle.net/E49Ey/

However it has nothing to do with Angular, except the data resides in the scope. If you have a DOM tree built from this data, then you could get the breadcrumb right from the DOM by going up the tree.

Solution 2:

Hey I put together a quick plunkr doing what your looking for... except it doesn't reverse-traverse up the data tree.

http://embed.plnkr.co/wAJYiAjy58vUEsg4Kr2C

If your looking to actually looking to run up the data tree let me know and I'll modify the plunkr

Solution 3:

You can of course solve it with a recursive function similar to what you showed in the question. What about a solution like this:

function getPath(obj, selNode, pathSoFar) {
    if (obj.roleName == selNode.roleName) {
       return pathSoFar + '\\' + obj.roleName;
    }
    elseif (obj.children) {
      for (var i=0 ; i<obj.children.length ; i++) {
          var temp = getPath(obj.children[i], selNode, 
                  pathSoFar + '\\' + obj.roleName);
          if (temp != null) {
              return temp;
          }
       }
    }
    returnnull;
}

getPath(rootObj, selNode, '');

I hope it helps and explains the solution idea.

Post a Comment for "Find All The Parents Of Each Element"