Skip to content

Instantly share code, notes, and snippets.

@ufhy
Created March 16, 2019 16:29
Show Gist options
  • Save ufhy/b93d3d1a421416749d861901d1879072 to your computer and use it in GitHub Desktop.
Save ufhy/b93d3d1a421416749d861901d1879072 to your computer and use it in GitHub Desktop.
Find all the parents of each element (hierarchy)
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" : []}
];// using the original data from your question
var index = {};
function buildIndex(root, children) {
for(var i in children) {
index[children[i].roleName] = root;
buildIndex(children[i].roleName, children[i].children);
}
}
buildIndex(false, tree);// first parameter evaluating to false means "no root"
console.log(index);
function getPath(leaf) {
return index[leaf] ? getPath(index[leaf]).concat([leaf]) : [leaf];
}
document.body.innerHTML = getPath("Cocker").join(" / ");// show the path to Cocker
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment