Discover the magic of parsing JSON child nodes using d3!

Having trouble parsing json data with d3. Below is the json structure:

{
  "name": "Main Course",
  ...
}//json data continues

I would like to generate a list based on this data, structured as follows:

<ul>
<li>Main Course</li>
  <ul>
  <li>Chinese</li>
    <ul>
    <li>Noodles</li>
    <li>Rice</li>
    <li>Xinjiang Roast</li>
    </ul>
  <li>Indian</li>
    <ul>
    <li>Rice</li>
    <li>Paratha</li>
    <li>Dal Fry</li>
    </ul>
  </ul>
</ul>

However, I am facing difficulties in my current approach:

d3.select("body")
        .append("ul")
        // More d3 code...

The result of my implementation so far is:

<ul>
<li id="mylist">Main Course<ul> ... </ul></li>
</ul>

I believe my issue lies in accessing the children nodes correctly. How can I effectively iterate through all the child elements and nest them under their respective parent nodes?

Answer №1

I personally believe that incorporating d3 for this task may be unnecessary.

Consider the following alternative approach:

function createMenu(data, container) {
    container = container || document.body;

    var ul = document.createElement('ul');
    var li = document.createElement('li');
    li.innerHTML = data.name;
    ul.appendChild(li);
    container.appendChild(ul);

    if(data.children) {
        for(var i=0; i<data.children.length; i++) {
            li = document.createElement('li');
            createMenu(data.children[i], li);
            ul.appendChild(li);
        }
    }
}

Check out a functional demonstration here.

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

Change the color of an icon when a button is clicked with the help of React

I'm new to React and facing an issue with updating like or bookmark count to 0 and 1 when a button is clicked. The problem arises when clicking on the bookmark icon, causing both icons to toggle inconsistently. ToggleIcon Component const ToggleIcon = ...

Easily transfer files without the need to refresh the page by utilizing the power of AJAX

In my page file-upload.jsp, I have the following code snippet: <form action="" id="frmupload" name="frmupload" method="post" enctype="multipart/form-data"> <input type="file" id="upload_file" name="upload_file" multiple="" /> <in ...

Jackson advises to disregard the properties of the parent class

Could I ask Jackson to not include properties from the parent class when serializing a child class? class Parent{ private String parentProperty1; private String parentProperty2; //getter setter } @IgnoreParentProperties ...

Parses JSON into a Dictionary with double keys and double array values

I'm trying to figure out how to store and read a JSON object that contains a Dictionary where the values are double arrays (Dictionary<double, double[]>). Most resources I've come across only address cases where the Dictionary's key-va ...

What is preventing the item from being added to the user's 'products' field in MongoDB using the $push command, even though the post was successfully made?

My goal is to seamlessly add a product and assign it to a customer's account by inserting it into the 'products' array in the database. I have opted to utilize the customer's email address, as the frontend interface simply requires an ...

Using a CSS style to modify a class based on another class at the same level in the hierarchy

I am working with a jQuery carousel that is adding an 'active' class to images within a div. Within the same div, there is also a span with a 'fade' class that has a CSS style of opacity: 0. Is there a way to change the CSS style of the ...

The content is not displayed in the d3 visualization

While examining the code of this visualization found at http://bl.ocks.org/mbostock/4062045, I noticed that the name from the JSON file is not displaying alongside the nodes. Even though the code includes: node.append("title").text(function(d) { return ...

Mastering the Art of Revealing and Concealing

I stumbled upon a great demonstration on reversing the Hide and Show functionality at https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_toggle_hide_show <!DOCTYPE html> <html> <head> <meta name="viewport" content="width ...

Discover the steps to incorporate an external JS file into Next.js 12

I am encountering an issue in my Next.js project when trying to import a local JS file. Here is the code snippet I am using: <Script type="text/javascript" src="/js.js"></Script> Unfortunately, this approach results in the ...

Tips for importing font files from the node_module directory (specifically otf files)

We cannot seem to retrieve the fonts file from the node module and are encountering this error message. Can't find 'assets/fonts/roman.woff2' in 'C:\Projects\GIT2\newbusinessapp\projects\newbusinessapp\src ...

Using JavaScript's regular expressions to locate a specific string that may span multiple lines

Is there a way to extract a specific substring from a string using regex even if the substring spans across multiple lines? I attempted to use the multiline flag in my regex pattern like this: "foo\nbar".match(/foobar/m) Unfortunately, this returns ...

Utilizing JavaScript values instead of relying on HTML values - a step-by-step guide

I am facing a challenge with 3 buttons that I have created: <button id="b1">0</button> <button id="b2">0</button> <button id="b3">0</button> Instead of retrieving the value from the HT ...

Optimizing the retrieval of large volumes of data from AWS S3 using Node.js, implementing pagination and efficiently delivering records to the frontend

Below is the code to fetch data from a CSV file in AWS S3 using Node.js backend. The challenge here is handling more than 200k records without consuming too much memory and efficiently returning it to the frontend. AWS.config.update({ accessKeyId: ...

Transforming XML into Json using HTML string information in angular 8

I am currently facing a challenge with converting an XML document to JSON. The issue arises when some of the string fields within the XML contain HTML tags. Here is how the original XML looks: <title> <html> <p>test</p> ...

How can Ext JS 4 handle the transmission of multiple metaData to support multiple dynamic grids by utilizing a single JSON file?

Looking to create multiple grids on a single panel using an accordion layout? I'll be dynamically generating all the grids based on metaData in JSON and handling metachange listener events on my store to reconfigure the grid. But here's the quest ...

The type 'number[]' is lacking the properties 0, 1, 2, and 3 found in the type '[number, number, number, number]'

type spacing = [number, number, number, number] interface ISpacingProps { defaultValue?: spacing className?: string disabled?: boolean min?: number max?: number onChange?: (value: number | string) => void } interface IFieldState { value: ...

How to Retrieve the Size Measurements of a 3D Model Using JavaScript

Currently, I am involved in an AR project that utilizes three.js and involves working with various 3D models. One issue I have encountered is the inconsistency in sizes among the models. I aim to have all the models of the same size, which requires setting ...

Find the nearest iframe relative to a parent element

I am attempting to find the nearest iframe element to a parent element in order to pinpoint the specific iframe that I want to customize using CSS: <div class ="accroche"> <iframe></iframe> <iframe></iframe> &l ...

Updating HTML Pages with Dynamic Content

Dealing with a massive project consisting of 50,000 pages (20,000 aspx forms, 10,000 asp forms, and 10,000 html pages) can be overwhelming. With only 2 days to complete the task of adding content after the body tag on all pages, I am seeking advice on ho ...

"Making a POST request from Postman and include nested JSON data along with an image or file attachment in

I have a JSON object that I need to POST: { "user": { "name": "John Doe", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87f2f4e2f5c7e2ffe6eaf7ebe2a9e4e ...