Created
March 16, 2019 16:29
-
-
Save ufhy/b93d3d1a421416749d861901d1879072 to your computer and use it in GitHub Desktop.
Find all the parents of each element (hierarchy)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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