Discover potential routes to nodes using JavaScript

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.

Answer №1

This code snippet demonstrates the implementation of a depth-first tree traversal algorithm 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}]};

browse({ children: object.records }, '', function (node, path) {
  if (!path) return;
  if (node.parent_id) path += ' (' + node.id + ')';
  print(path);
});

function browse (tree, path, forEachNode) {
  var i, node;
  var nodes = tree.children;
  var l = nodes ? nodes.length : 0;
  forEachNode(tree, path);
  if (path !== '') path += ' -> ';
  for (i = 0; i < l; i++) {
    node = nodes[i];
    browse(node, path + node.name, forEachNode);
  }
}

function print (html) {
  document.body.innerHTML += html + '<br />';
}

Answer №2

What do you think of this?

var data = {"info":{"count":6,"page":1,"limit":5},"items":[{"name":"Electronics","id":123,"parent_id":0,"children":[{"name":"Phones","id":145,"parent_id":123,"children":null},{"name":"Laptops","id":146,"parent_id":123,"children":null}]},{"name":"Toys","id":124,"parent_id":0,"children":null},{"name":"Clothing","id":125,"parent_id":0,"children":null}]};
  
function displayCategories(items, prefix) {
    var el = document.getElementById("categories");
     _.each(items,function(item){
         
         el.innerHTML += prefix + item.name + (prefix ? ' ' + item.id: '') + '<br>';

         if(item.children) {
             displayCategories(item.children, prefix + item.name + ' -> ');
         }
        
      });
}

displayCategories(data.items, '')
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<div id="categories"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generate TypeScript type definitions for environment variables in my configuration file using code

Imagine I have a configuration file named .env.local: SOME_VAR="this is very secret" SOME_OTHER_VAR="this is not so secret, but needs to be different during tests" Is there a way to create a TypeScript type based on the keys in this fi ...

Creating an event declaration using Javascript's onclick function

As I was getting ready to add an onclick event to my element in JavaScript, a question popped into my mind regarding the efficiency of these two options: document.getElementById(myid).onclick = function(e){...} or document.body.onclick = fun ...

After attempting to follow a guide, I encountered a scenario where a view was returning None because the is_ajax function was not

After diving into the world of ajax, I encountered a puzzling issue that I can't seem to crack. My hunch is that it involves the comment_id versus the blog_id. (I was following this tutorial: https://www.youtube.com/watch?v=VoWw1Y5qqt8&list=PLKILt ...

Store the result of the previous AJAX call in a jQuery variable and combine it with the data from the next AJAX response

I am working on a program where I retrieve price values using ajax. My goal is to add the previous price value to the current price value when it is retrieved again. The issue I am facing is that each time I get a new price value, it overrides the previou ...

Is it possible to incorporate knockout.js within a Node.js environment by utilizing .fn extensions in custom modules?

I'm currently exploring the possibility of implementing the knockout.mapping.merge library in node.js, but I seem to be facing a challenge when it comes to extending ko objects within the module's scope. I am struggling to figure out how to exten ...

JQuery displays 'undefined' on checkbox loaded via Ajax

Currently, I am utilizing a checkbox to activate my select Option tag. The select option tag and checkbox are both loaded via ajax. While the select option works perfectly, the checkbox displays as undefined. However, it functions properly in enabling my d ...

How can a JavaScript function communicate with a code behind method?

Currently, I am trying to implement a JavaScript function for an HTML img click event on an aspx page. Additionally, there is a server method in the code behind page that I need to call from the JavaScript function without any parameters whenever the user ...

Encountering an issue when passing a response using coverage.js

I am utilizing coverage.js to showcase data. When I pass my variable containing the coverage response into an HTML file, similar to how it's done in Angular to display expressions, I encounter a syntax error: <div class="container" style="margin- ...

Next.JS is having trouble importing the URL class from the 'url' module in Node

Recently, while developing with next.js and webpack 5, I encountered an issue where my URL class import stopped working unexpectedly. Upon running npm run build, the following error message appeared: Attempted import error: 'URL' is not export ...

Exploring the Adjustment of State as well as Function in Next/React JS

I'm facing a challenge in my React project where I need to manage state and trigger a function across separate component files. Specifically, I have my main app file along with two components (header and sidebar) stored in the components folder. The h ...

Encountering timeout issues with Next.JS fetch and Axios requests on Vercel production environment

I've been encountering an issue where I am unable to fetch a specific JSON data as it times out and fails to receive a response on Vercel deploy. The JSON data I'm trying to fetch is only 18KB in size and the fetch request works perfectly fine in ...

Ensure that JavaScript functions are executed sequentially without overlapping

Important : Absolutely no jQuery allowed I have developed four distinct functions and I am looking to execute them sequentially, one after the other in JavaScript without using jQuery. I have scoured the internet for a solution but unfortunately have not ...

Following the ajax request, the subsequent code was unable to be executed as it awaited the JSON response

My latest project involves using Django2 to create a web application. I encountered an issue in the frontend where, despite receiving a 200 status code in the network tab after an ajax call, no alert box was displayed. The app seemed to be stuck at a parti ...

Error: The variable "message" has not been defined. Please define it before displaying the welcome

While I was experimenting with my welcome message and attempting to convert it into an embed, I ended up rewriting the entire code to make it compatible. However, upon completion, I encountered the error message is not defined. var welcomePath = './ ...

Encountering an error: Reading an undefined property - NodeJS, Express, and Mongoose

These are the two functions I have: exports.list = function (req, res){ Material.find(function(err, materials) { res.render('materials/list', {title: 'Pagina Materiali', materials: materials}); }); } exports.modify = function (req ...

React issue: parent state becoming unresponsive when updating during input onChange event

I am currently working on a large form that consists of at least 50 input fields. I have developed a function within the form component to store the input values in the form's state: PARENT FUNCTION saveToState(details) { const { company } = thi ...

Assign an AJAX call to retrieve data from a MySQL table and store it in a

In my database, I have a table that includes fields for 'user_name' and 'user_round'. My goal is to set the 'user_round' field to match the value of a JavaScript variable called 'Level'. However, when I run my code, ...

Tips for utilizing Vue router query parameters while in hash mode:

Is there a more efficient way to access URL parameters in Vue methodology, without having to rely on window.location.href and parsing the URL? router/index.js const router = new Router({ mode: 'hash', routes: [] }); router.beforeEach((to, f ...

Error: Unable to modify a property that is marked as read-only on object '#<Object>' in Redux Toolkit slice for Firebase Storage in React Native

Hey there! I've been working on setting my downloadUrl after uploading to firebase storage using Redux Toolkit, but I'm facing some challenges. While I have a workaround, I'd prefer to do it the right way. Unfortunately, I can't seem to ...

The Data Table experiences intermittent hanging issues (Table is empty) when sorting or loading data with Knockout binding

While working on a project, I encountered an issue with binding data to a table using Knockout JS and the JQuery/Bootstrap based; Data Table API. The problem was that the table would become unresponsive at times when sorted or loaded, without any errors be ...