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

What is the best way to include basic static files and HTML together in a NodeJS environment?

I am facing an issue trying to serve an HTML file with its CSS and JS files in NodeJS using express.static(), but unfortunately, it is not working as expected. I have followed the steps shown in several tutorials, but for some reason, the output is not co ...

Filtering objects in AngularJS is a complex task, especially when you need to be able to search for a specific value but also consider if that value exists

Struggling to convey my thoughts in English, but here it goes. Imagine two objects linked by colorid: $scope.fruits = {{name:"apple",colorid:"1"},etc}; $scope.colors = {{id:"1",value:"red"}; I've created a table with search and filter function ...

Is there a way to retrieve the title, description, and image URL of a URL through Ajax, similar to how Facebook shares a link?

Currently, I am developing a project that involves allowing users to submit a URL. The system will then extract the title, images, and description from the provided URL and offer the option to toggle between different images. Upon submission, these extrac ...

I'm experiencing an issue with loading the GeoJSON file on my localhost

I included this vector into my local host code, but the JSON file does not seem to load. geojson_layer = new OpenLayers.Layer.Vector("features", { projection: epsg4326, strategies: [new OpenLayers.Strategy.Fixed()], pro ...

Combine the values in the array with the input

I received some data from the back-end which is being written to a form, and it's in the form of an array of objects Below is the code snippet: this.companyDetailsForm = new FormGroup({ directors : new FormControl(response?.companyDirectors) ...

Troubleshooting issues when testing Angular services using Jasmine and Chutzpah

I've been facing some challenges while attempting to test my AngularJs services with Jasmine as I encounter various errors consistently. In an effort to troubleshoot, I decided to create a simple Sum service for testing purposes but unfortunately, the ...

The request.body in Express.js is currently undefined

const express = require('express'); const cors = require('cors'); const app = express(); app.use(express.json()) app.use(cors()); app.post('/', (req,res) => { console.log(req.body); res.send('received') ...

The inserted button's click event does not trigger the contentEditable DIV

I have a contentEditable DIV that I manage using the directive below: <div class="msg-input-area" [class.focused]="isMsgAreaFocused" contenteditable [contenteditableModel]="msgText" (contenteditableModelChang ...

Are there any conventional methods for modifying a map within an Aerospike list?

Attempting to modify an object in a list using this approach failed const { bins: data } = await client.get(key); // { array: [{ variable: 1 }, { variable: 2 }] } const { array } = await client.operate(key, [Aerospike.maps.put('array', 3).withCon ...

Previewing multiple images with multiple file inputs

I am trying to find a way to preview multiple images uploaded from different inputs. When the button is pressed, the content from a textarea containing <img src="$img" id="img1"> is written inside a div called seeimg. The IDs for these images range f ...

Challenges Encountered When Working with React.useState()

I am facing an issue where a new row is not appearing after clicking the button. Although the console.log output indicates that the row was added correctly to the tables variable. Another concern I have is why I can see the new row added to the table even ...

Tips for accessing various JSON objects from a JSON document

My task involves extracting specific information from a JSON file using AJAX and jQuery. The structure of my JSON data is as follows: "Footwear": { "Adidas": [ { "id" : 0, &q ...

How to extract data from a JSON file in a different JAR using

Currently, I am working on creating a system for modules/addons and I need to read a "module.json" file from all the loaded modules/addons in a specific directory. I have managed to loop through the files successfully, but I am facing challenges in acces ...

Optimizing your approach to testing deferred always

When creating test cases for code within a jQuery AJAX call's always method or in bluebird promises' finally function, it often involves the following structure: function doStuff() { console.log('stuff done'); } function someFunct ...

Displaying Image Preview in Angular 2 After Uploading to Firebase Storage

At the moment, I am facing an issue where the uploaded image is not being displayed after the uploadTask is successful. This problem arises due to the asynchronous loading nature of the process, causing the view to attempt to display the image before the u ...

Determining the victorious player in a game of Blackjack

After the player clicks "stand" in my blackjack game, my program checks for a winner. I am using AJAX to determine if there is a winner. If there is a winner, an alert will display their name. Otherwise, the dealer will proceed with making their move. Any ...

Guide to counting the number of image tags within a parent div and selectively removing them starting from a specific position

My dynamic image tag <img> is generated inside a div from the database using fetching. Here is how my HTML looks: <div class='forimgbox'> <p class='palheading'>Pals</p> <img src='userpic/2232323.p ...

The Gusser Game does not refresh the page upon reaching Game Over

Hi there, I am a beginner in the world of JavaScript and currently working on developing a small guessing game app. However, I have encountered an issue where the page is not reloading after the game is over and the 'Play Again' button appears to ...

Angular and JS do not have the functionality to toggle the split button

I have a question that seems similar to others I've seen, but I haven't found a solution yet. Can someone please review my code? In the component, I have {{$ctrl.init}} and {{$ctrl.people}} assigned. I am sure this assignment is correct because ...

What is the correct way to properly wrap the div component in this code snippet?

I am currently working on implementing a Javascript component that displays pinned locations and related information on a map. I have made some progress with the implementation, but unfortunately, it does not appear correctly in the actual site. There is a ...