A JSON array that is flat in structure looks like this:
var flatObject =
[
{ id : "1", parentId : "0", name : "object 1" },
{ id : "2", parentId : "1", name : "object 2" },
{ id : "3", parentId : "2", name : "object 3" },
{ id : "4", parentId : "3", name : "object 4" },
{ id : "5", parentId : "4", name : "object 5" },
{ id : "6", parentId : "5", name : "object 6" },
{ id : "7", parentId : "1", name : "object 7" },
{ id : "8", parentId : "1", name : "object 8" },
{ id : "9", parentId : "1", name : "object 9" }
];
To display a hierarchy based on an ID by traversing through parent IDs, we need to simplify the existing code. Although I know the depth is fixed at 5 levels, the current function has a lot of redundant lines. Let's consider using recursion for a more concise solution. Here is the original function:
function getItems(id){
if(!id){
document.getElementById("demo").innerHTML = "";
id = document.getElementById("hvitems").value;
}
for(a=0;a<flatObject.length;a++){
var objA = flatObject[a];
var objIdA = objA.id;
if(objIdA == id){
var objNameA = objA.name;
document.getElementById("demo").innerHTML += "(" + objIdA + ") " + objNameA + "<br>";
// look for parentIds matching the current Id
for(b=0;b<flatObject.length;b++){
var objB = flatObject[b];
var objIdB = objB.id;
var objParentIdB = objB.parentId;
if(objParentIdB == objIdA){
var objNameB = objB.name;
document.getElementById("demo").innerHTML += " - (" + objIdB + ") " + objNameB + "<br>";
// recursively search for parentIds
for(c=0;c<flatObject.length;c++){
var objC = flatObject[c];
var objIdC = objC.id;
var objParentIdC = objC.parentId;
if(objParentIdC == objIdB){
var objNameC = objC.name;
document.getElementById("demo").innerHTML += " -- (" + objIdC + ") " + objNameC + "<br>";
// continue searching for parentIds
}
}
}
}
}
}
}
getItems(1);
// or getItems(3); ...
The hierarchical output can be observed within this div:
<div id="demo"></div>
Although functional, there may be room for improvement in terms of efficiency and readability. Learning and utilizing recursion could greatly optimize this process.
To view the full example, check out the live demo.