I need assistance displaying all potential node paths in JavaScript:
var object = {"metadata":{"record_count":5,"page_number":1,"records_per_page":5},"records":[{"name":"Kitchen","id":666,"parent_id":0,"children":null},{"name":"Jewellery","id":667,"parent_id":0,"children":null},{"name":"BabyProducts","id":668,"parent_id":0,"children":null},{"name":"Books","id":669,"parent_id":0,"children":[{"name":"Story Books","id":689,"parent_id":669,"children":[{"name":"Children's Story Books","id":690,"parent_id":689,"children":null}]}]},{"name":"Apparel","id":670,"parent_id":0,"children":null}]};
function formCategoryTrees(object, parentNode) {
var div = document.getElementById("output");
_.each(object,function(objectValues){
var leafCategoryId = objectValues["id"];
var leafCategoryName = objectValues["name"];
if(parentNode === null){
div.innerHTML = div.innerHTML + leafCategoryName + "</br>";
} else {
div.innerHTML = div.innerHTML + parentNode + "->" + leafCategoryName + " " + leafCategoryId + "</br>";
}
var hasChildren = objectValues.hasOwnProperty("children");
var childValue = objectValues["children"];
if(hasChildren && childValue !== null) {
formCategoryTrees(objectValues["children"], leafCategoryName);
}
});
}
formCategoryTrees(object.records, null);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<div id="output"></div>
https://jsfiddle.net/tfa8n5tj/3/
The current outcome is:
Kitchen
Jewellery
BabyProducts
Books
Books->Story Books 689
Story Books->Children's Story Books 690
Apparel
However, the desired display is:
Kitchen
Jewellery
BabyProducts
Books
Books->Story Books 689
Books->Story Books->Children's Story Books 690
Apparel
Please assist me in achieving this result.