Transforming intricate JSON data into a structured table format

I'm struggling to transform the nested JSON data into an HTML table, but I keep encountering an error.

I'm uncertain about where I may have made a mistake. Could it be related to how I am trying to access the array within the object?

Here's the specific error message that keeps popping up:

"Cannot set property 'innerHTML' of null"

Below is the code snippet I have written:

function DonutTable(array){
    // create a table element
    var table = document.createElement("table");
    // create header columns

    var col = Object.keys(array[0]); // array of keys
    // display keys in the header cell
    var tr = table.insertRow(-1);
    col.forEach(function(key){
        var th = document.createElement("th");
        th.textContent = key;
        tr.appendChild(th);
    });

    // create rows to contain the rest of the data
    array.forEach(function(obj){
        // for each obj in the main array, create a row
        var data_row = table.insertRow(-1);
        // populate data for each column in the col array
        col.forEach(function(key){
            var tabCell = data_row.insertCell(-1);
            if (key==="batters"){
                // retrieve the value of batters and access batter values
                obj["batters"]["batter"].forEach(function(e){
                    // for each e in batter, create a div element
                    var div = document.createElement("div");
                    // write on the div 
                    div.textContent =  e.type + "(" + e.id + ")";
                    tabCell.appendChild(div); })
                }
            if (Array.isArray(obj[key])){ // check if the value of a key is an array
                obj[key].forEach(function(topping){
                    // for each topping object, get id and type 
                    var div = document.createElement("div");
                    div.textContent =  topping.type + "(" + topping.id + ")";
                    tabCell.appendChild(div);
                })
            }
            else{
                tabCell.textContent = obj[key];
            }


                })
            })


    var divContainer = document.getElementById("showTable");
    divContainer.innerHTML = "";
    divContainer.appendChild(table);

}

var donut = [
    {
        "id": "0001",
        "type": "donut",
        "name": "Cake",
        "ppu": 0.55,
        "batters":
            {
                "batter":
                    [
                        { "id": "1001", "type": "Regular" },
                        { "id": "1002", "type": "Chocolate" },
                        { "id": "1003", "type": "Blueberry" },
                        { "id": "1004", "type": "Devil's Food" }
                    ]
            },
        "topping":
            [
                { "id": "5001", "type": "None" },
                { "id": "5002", "type": "Glazed" },
                { "id": "5005", "type": "Sugar" },
                { "id": "5007", "type": "Powdered Sugar" },
                { "id": "5006", "type": "Chocolate with Sprinkles" },
                { "id": "5003", "type": "Chocolate" },
                { "id": "5004", "type": "Maple" }
            ]
    },
    {
        "id": "0002",
        "type": "donut",
        "name": "Raised",
        "ppu": 0.55,
        "batters": 
            {
                "batter":
                    [
                        { "id": "1001", "type": "Regular" }
                    ]
            },
        "topping":
            [
                { "id": "5001", "type": "None" },
                { "id": "5002", "type": "Glazed" },
                { "id": "5005", "type": "Sugar" },
                { "id": "5003", "type": "Chocolate" },
                { "id": "5004", "type": "Maple" }
            ]
    },
    {
        "id": "0003",
        "type": "donut",
        "name": "Old Fashioned",
        "ppu": 0.55,
        "batters":
            {
                "batter":
                    [
                        { "id": "1001", "type": "Regular" },
                        { "id": "1002", "type": "Chocolate" }
                    ]
            },
        "topping":
            [
                { "id": "5001", "type": "None" },
                { "id": "5002", "type": "Glazed" },
                { "id": "5003", "type": "Chocolate" },
                { "id": "5004", "type": "Maple" }
            ]
    }
]
DonutTable(donut);

<html>
    <head>
        <title>Converting JSON Data to HTML Table Example</title>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
        <input type="button" value="Generate Table" onclick="DonutTable()">
        <div id="showTable"></div>
    </body>
</html>

Answer №1

To debug the issue in Chrome, try setting a breakpoint immediately after declaring your divContainer variable. It appears that the divContainer is null due to JavaScript being executed before the corresponding HTML elements are loaded on the page. You can resolve this by either encapsulating the JS code within a document.ready function or rearranging the script section below the HTML content.

Answer №2

Here's your code divided into JavaScript and HTML sections:

The code runs properly initially because the donut array is explicitly passed to the DonutTable() function. However, it won't work when the button is clicked because the HTML does not pass any parameters to DonutTable().

function DonutTable(array){
    //create a table element
    var table = document.createElement("table");
    //create header columns

    var col = Object.keys(array[0]); //array of keys
    //write keys onto the header cell
    var tr = table.insertRow(-1);
    col.forEach(function(key){
        var th = document.createElement("th");
        th.textContent = key;
        tr.appendChild(th);
    });

    //create rows to hold the rest of the data
    array.forEach(function(obj){
        //for each obj in the main array, create a row
        var data_row = table.insertRow(-1);
        //for each header in the col array, populate data
        col.forEach(function(key){
            var tabCell = data_row.insertCell(-1);
            if (key==="batters"){
                //grab the value of batters and access value of batter
                obj["batters"]["batter"].forEach(function(e){
                    //for each e in batter, create a div element
                    var div = document.createElement("div");
                    //write on the div 
                    div.textContent =  e["type"] + "(" + e["id"] + ")";
                    tabCell.appendChild(div); })
                }
            else if (Array.isArray(obj[key])){ //check if a value of a key is an array
                obj[key].forEach(function(topping){
                    //for each obj in topping, get id and type 
                    var div = document.createElement("div");
                    div.textContent =  topping.type + "(" + topping.id + ")";
                    tabCell.appendChild(div);
                })
            }
            else{
                tabCell.textContent = obj[key];
            }


                })
            })


    var divContainer = document.getElementById("showTable");
    divContainer.innerHTML = "";
    divContainer.appendChild(table);

}

var donut = [
    {
        "id": "0001",
        "type": "donut",
        "name": "Cake",
        "ppu": 0.55,
        "batters":
            {
                "batter":
                    [
                        { "id": "1001", "type": "Regular" },
                        { "id": "1002", "type": "Chocolate" },
                        { "id": "1003", "type": "Blueberry" },
                        { "id": "1004", "type": "Devil's Food" }
                    ]
            },
        "topping":
            [
                { "id": "5001", "type": "None" },
                { "id": "5002", "type": "Glazed" },
                { "id": "5005", "type": "Sugar" },
                { "id": "5007", "type": "Powdered Sugar" },
                { "id": "5006", "type": "Chocolate with Sprinkles" },
                { "id": "5003", "type": "Chocolate" },
                { "id": "5004", "type": "Maple" }
            ]
    },
    {
        "id": "0002",
        "type": "donut",
        "name": "Raised",
        "ppu": 0.55,
        "batters": 
            {
                "batter":
                    [
                        { "id": "1001", "type": "Regular" }
                    ]
            },
        "topping":
            [
                { "id": "5001", "type": "None" },
                { "id": "5002", "type": "Glazed" },
                { "id": "5005", "type": "Sugar" },
                { "id": "5003", "type": "Chocolate" },
                { "id": "5004", "type": "Maple" }
            ]
    },
    {
        "id": "0003",
        "type": "donut",
        "name": "Old Fashioned",
        "ppu": 0.55,
        "batters":
            {
                "batter":
                    [
                        { "id": "1001", "type": "Regular" },
                        { "id": "1002", "type": "Chocolate" }
                    ]
            },
        "topping":
            [
                { "id": "5001", "type": "None" },
                { "id": "5002", "type": "Glazed" },
                { "id": "5003", "type": "Chocolate" },
                { "id": "5004", "type": "Maple" }
            ]
    }
]
DonutTable(donut);
<html>
    <head>
        <title>HTML Donut Table from JSON</title>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
        <input type="button" value="Generate a table" onclick="DonutTable()">
        <div id="showTable"></div>
    </body>
</html>

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

Preventing multiple clicks by toggling the HTML tag on and off

Here is the jQuery structure that I am currently working with: $(document).on('click', '.view-details', function () { $(this).prop("disabled", true); // API call1 // API call2 // API call3 $(this).prop("disabled" ...

What could be causing the inability to move down on this page?

Trying to scroll down a page using Selenium with Python and the execute_script command, but encountering issues. Despite executing the code provided below, I am unable to reach the bottom of the page: def create_browser(first_page=None): print "Starti ...

Determine whether AngularJS directive method binding automatically defaults to angular.noop

In my directive, I am passing a function to a plugin which will use it with a specified value. Let's simplify things by ignoring data changes: angular.module('some.directives', []) .directive('myDirective', [, function () { ...

Using THREE.js: Finding the nearest point between two rays in a THREE.js environment

In my current project with THREE.js, I am working with two THREE.Ray objects. Both rays have an origin point represented by a Vector3 and a direction indicated by another Vector3. I am currently exploring how to determine the nearest intersection point be ...

Having trouble properly serializing JSON with JSON.NET

My process involves using JSON.net to convert highly complex XML into JSON and then deserializing it into C#. string text = await blockBlob2.DownloadTextAsync(); XmlDocument doc = new XmlDocument(); doc.LoadXml(text); string json = Newtonsoft.Json.JsonCo ...

The pagination feature for Swiper is experiencing issues across both desktop and mobile platforms

I am having an issue with the pagination display in the text. I would like it to appear below the text as a standalone item for better visibility. Another problem arises when viewing the page on mobile devices - the hamburger menu displays behind the slid ...

Errored Out: No content found in file_get_contents('php://input') following an ajax post

I've run into a dilemma and am seeking help. I recently encountered an issue where data sent to a PHP file through an AJAX function seemed to vanish when attempting to retrieve it in the PHP file. Strangely enough, a similar function I implemented yes ...

Troubleshooting Problems with CSS `transform` in JQuery UI's `Slide` Transition

While implementing JQueryUI's slide transition on an element with a CSS transform, I encountered an issue where the top half of the element gets hidden during the animation. Is there a way to tweak either my JQueryUI animation or CSS to avoid this pro ...

Error encountered: API key is required - Issue found in: /node_modules/cloudinary/lib/utils.js at line 982

I encountered an issue with cloudinary while trying to upload photos on my website after adding a new function for Facebook login. "/home/ubuntu/workspace/YelpCamp/node_modules/cloudinary/lib/utils.js:982 throw "Must supply api_key"; ^ Mus ...

Tips for extracting information from Firebase and showing it on a Google gauge chart

I'm having some trouble displaying data from Firebase on a gauge chart. I keep getting an error that says "Uncaught (in promise)". Here's the JavaScript code I've been working with: <script type="text/JavaScript"> google.ch ...

Establishing a dynamic database feature (such as a real-time leader board) on a website

Recently, I designed a fun JavaScript game for my website and now I am contemplating adding a leaderboard feature. However, I am unsure about which type of database would be the best fit - MongoDB, SQLite, or something else entirely. I have heard that SQ ...

Utilizing Ajax and jQuery to extract information from an XML file based on an identification number

Currently, I am looking for a way to showcase a specific product with its description from my XML file by using the product's ID. The structure of my XML file is shown below: https://i.sstatic.net/wFWgW.png Below is the JavaScript code I am using: ...

Having difficulty with express.index when trying to send a JSON object

Express is my tool of choice for creating a simple web page. The code in my index.js file looks like this: exports.index = function(req, res){ res.render( 'index', { title: 'Expressssss', Tin: va ...

How can an array of file paths be transformed into a tree structure?

I am looking to transform a list of file and folder paths into a tree object structure (an array of objects where the children points to the array itself): type TreeItem<T> = { title: T key: T type: 'tree' | 'blob' childr ...

The process of generating collection names dynamically based on user information

My goal is to enhance the structure of my data collection and make it more organized. While I am familiar with accessing and retrieving data, I am unsure about creating the schema. Here is my current schema: var MySchema = new Schema ({ event: { ...

How to request permissions from a bot user in Discord.js version 14?

I need to verify my bot's permissions before it carries out a command. Previously, everything was functioning perfectly with this code: // Discord.js v13 if (interaction.guild.me.permissions.has(Permissions.FLAGS.MANAGE_MESSAGES)) { interaction.re ...

Display the data received from the client on the NodeJS server

I have a basic html file that includes the following snippet of javascript: <script type="text/javascript"> $.ajax({ url: 'http://192.168.X.X:8080', data: '{"data": "1"}', dataType: ...

Issue with the gulp-babel plugin: Files within the Plugin/Preset should only export functions, not objects

I have started to integrate JavaScript 2015 (ES6) into my Ionic v1 app: package.json { "name": "test", "version": "1.0.0", "dependencies": { "@ionic-native/deeplinks": "^4.18.0", "cordova-android": "7.0.0", "cordova-android-support-gra ...

What is the best way to send a REST API request with escaped double quotes?

I need to transmit a REST API request to my server with data that must be in the form of a string enclosed with double quotes: data=mycontent curl -X POST "$SERVER_ENDPOINT" \ -H 'Authorization: Bearer '"$SERVER_TOKEN&qu ...

Unraveling the mystery: How does JavaScript interpret the colon?

I have a quick question: When I type abc:xyz:123 in my GoogleChrome browser console, it evaluates to 123. How does JavaScript interpret the : symbol in this scenario? ...