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

ensure that only one option can be selected with the checkbox

Can someone help me with applying this code on VueJS? I tried replacing onclick with @click but it's not working for me. I'm new to VueJS, so any guidance would be appreciated! function onlyOne(checkbox) { var checkboxes = document.getElement ...

The async and await functions do not necessarily wait for one another

I am working with Typescript and have the following code: import sql = require("mssql"); const config: sql.config = {.... } const connect = async() => { return new Promise((resolve, reject) => { new sql.ConnectionPool(config).connect((e ...

Having issues with the functionality of the Material UI checkbox component

Having issues with getting the basic checked/unchecked function to work in my react component using material UI checkbox components. Despite checking everything, it's still not functioning as expected. Can someone please assist? Here's the code s ...

Is there a way to efficiently parse and categorize erroneous JSON data in JavaScript?

Resolved my issue var allKeys = ["key","en","ar"]; for(var i=0;i<allKeys.length;i++) { for(j=0;j<jsonText.Sheet1.length;j++) { console.log(allKeys[i] + ' - ' + jsonText.Sheet1[j][allKeys[i]]); } } Live demonstration Appreciation ...

Generate fake data for all possible combinations using JSON faker

In my current project, I am in need of creating test data for a JSON schema. I came across this fantastic github resource that has been incredibly helpful: https://www.npmjs.com/package/json-schema-faker#overview Now, how can we expand it to generate all ...

Vue error: Uncaught promise rejection - RangeError: The computed value update has exceeded the maximum call stack size

My computed code snippet: computed: { display: { get() { return this.display }, set(newValue) { this.display = newValue } } }, Attempting to update the computed value from a function in ...

Transforming a PHP cURL call to node.js

Currently exploring the possibility of utilizing the Smmry API, however, it seems that they only provide PHP API connection examples. Is there anyone who could assist me in adapting it into a JS request? My requirement is simple - I just need it to analyz ...

Develop a constructor that can be injected

Delving into the world of AngularJS as a beginner, I am starting to grasp the intricacies and distinctions between factory, service, and controller. From my understanding, a factory serves the purpose of returning a "value object" that can be injected. Mos ...

Can Regex expressions be utilized within the nodeJS aws sdk?

Running this AWS CLI command allows me to retrieve the correct images created within the past 45 days. aws ec2 describe-images --region us-east-1 --owners self -- query'Images[CreationDate<`2021-12-18`] | sort_by(@, &CreationDate)[].Name&apos ...

In order to ensure proper alignment, adjust the width of the select element to match the width of the

Is there a way for the select element to adjust its width based on the length of the selected option? I want the default option value's width to be shorter, but once another option is selected, I'd like the select element to resize itself so that ...

Guide to retrieving data from a URL and storing it in a string variable with JavaScript

Attempting to retrieve the JSON data from a specific URL and store it in a variable. The code snippet below successfully loads the JSON into a div element: $("#siteloader").html('<object data="MYURL">'); However, the goal is to extract t ...

Error message displayed: "Unexpected token 'H' when attempting to render Markdown

I've been working with the react markdown library and wanted to share my code: import Markdown from 'react-markdown'; import PreClass from './PreClass'; type MarkdownFormatTextProps = { markdown: string; tagName?: string; ...

Encountering issues with integrating interactjs 1.7.2 into Angular 8 renderings

Currently facing challenges with importing interactive.js 1.7.2 in Angular 8. I attempted the following installation: npm install interactjs@next I tried various ways to import it, but none seemed to work: import * as interact from 'interactjs'; ...

What could be preventing the fill color of my SVG from changing when I hover over it?

I am currently utilizing VueJS to design an interactive map showcasing Japan. The SVG I am using is sourced from Wikipedia. My template structure is illustrated below (The crucial classes here are the prefecture and region classes): <div> <svg ...

Looking to pass the `Item Index` to functions within v-list-item-action in Vuetify?

Is there a way to pass the item index as a parameter to the function within the v-list-item-action element? Thank you in advance! <v-list-item v-for="(layer, i) in layers" :key="i"> <template v-slot="{ item, index }& ...

The command "Npm Start Causes sleep is not accepted" just popped up

After cloning a React project from GitHub, I proceeded to run npm install, which successfully installed the node_modules folder. However, upon trying to run npm start, I encountered the following error: 'sleep' is not recognized as an internal or ...

Finding the following index value of an object within a foreach loop

In my code, I have an object called rates.rates: { AUD="1.4553", BGN="1.9558", BRL="3.5256"} And I am using the following $.each loop: $.each( rates.rates, function( index, value ){ console.log(index); }); I have been attempting to also log the n ...

issue with transparent html5

Here is the code snippet I am struggling with: function clear(){ context2D.clearRect(0, 0, canvas.width, canvas.height); } function drawCharacterRight(){ clear(); context2D.setTransform(1, 0.30, 1, -0.30, 10, 380);//having issues here c ...

The browser encountered an issue trying to load a resource from a directory with multiple nested levels

I've stumbled upon an unusual issue. Here is a snapshot from the inspector tools. The browser is unable to load certain resources even though they do exist. When I try to access the URL in another tab, the resource loads successfully. URLs in the i ...

I am currently exploring React Router, but I am struggling to grasp this particular behavior

My Express server serves the Create-React-App build. When I access http://localhost:8000/ while the server is listening, my page loads correctly. However, if I reload the page or navigate directly to it from the navigation bar, instead of seeing the UI, pl ...