Attempting to generate tables from JSON containing numerous "table" sections

Hello there. My goal is to generate tables from the JSON data I've received. While creating a table works fine with a single block of JSON, I face challenges when dealing with multiple blocks for multiple tables. Below you'll find an example of JSON containing data for two tables, along with the JavaScript code I have so far to insert the table into the HTML document. Any advice or suggestions on this matter would be greatly appreciated. Thank you in advance.

[
{
    "table": {
        "tableDetails": [
            {
                "filecreatedate": "8/28/2014 10:43:08 AM",
                "Name": "Personal Loans",
                "PrintUrl": "print friendly url here",
                "EffectiveDate": "3/7/2014",
                "disclosure": "disclosure "
            }
        ],
        "headers": [
            {
                "Header1": "Personal Loans",
                "Header2": "Loan Amount",
                "Header3": "Fee",
                "Header4": "APR",
                "Header5": "Calculator"
            }
        ],
        "columns": [
            {
                "PersonalLoans": "VISA Platinum Rewards",
                "LoanAmount": "$1000 - $25,000",
                "Fee": "$0.00",
                "APR": "9.15%",
                "Calculator": "<a href='#'><img src='img/calc.gif' alt='Calculator' /></a>"
            },
            ...
        ]
    }
},
{
    "table": {
        "tableDetails": [
            {
                "filecreatedate": "8/28/2014 10:43:34 AM",
                "Name": "Fixed Rate Second Mortgage",
                "PrintUrl": "print friendly url here",
                "EffectiveDate": "5/1/2014",
                "disclosure": "disclosure text"
            }
        ],
        "headers": [
            {
                "Header1": "Loan Amount",
                "Header2": "APR LTV <=80%",
                "Header3": "APR LTV 80.01-90%",
                "Header4": "Note",
                "Header5": "Calculator"
            }
        ],
        "columns": [
            {
                "Loan Amount": "$50,000+",
                "APR LTV <=80%": "5.950%",
                ...
            },
            ...
        ]
    }
}

]

And here's the associated JS code:

$("table#tbl").wrap("<div class='rate_table' />");
$("table#tbl").append("<tbody></tbody>");
var data = {};
$.getJSON("path/taken/out/for/SO", function(response) {
data = response;
$.each(data, function(index, item) {
    for (var i = 0; i < item.table.tableDetails.length; i++) {
        $("table#tbl").before(item.table.tableDetails[i].Name);
    }
});
...
});

The final output should look like this:

<table id="tbl">
<thead></thead>
</table>
<p class="rateDisclosure">&nbsp;</p>

Answer №1

When dealing with JSON data, it's important to process it dynamically rather than relying on static elements. By injecting the table element instead of placing it directly in the HTML, you can create tables in a loop.

If you're only interested in the first index of the data and don't need to iterate through all the tables, you can simply pass it through your rendering function without looping.

For an example of how to dynamically render multiple tables using JSON data, check out this fiddle: http://jsfiddle.net/6wdksrkp/2/

Here is the code solution for you:

$.getJSON("path/taken/out/for/SO", function(tables) {
    // This code should be placed inside your AJAX callback function
    if (tables) {
        for (var i = 0, len = tables.length; i < len; i++) {
            RenderTable(tables[i]);
        }
    }
}

function RenderTable(tableDef) {
    var $tbl = $("<table><thead></thead><tbody></tbody></table>");
    
    $tbl.wrap("<div class='rate_table' />");
    
    var jsonData = tableDef;
    $.each(jsonData, function (index, object) {
        for (var j = 0; j < object.tableDetails.length; j++) {
            $tbl.before(object.tableDetails[j].Name);
        }
    });

    $.each(jsonData, function (index, object) {
        for (var j = 0; j < object.headers.length; j++) {
            $tbl.children("thead").append('<th class="col_0">' + object.headers[j].Header1 + '</th><th class="col_1">' + object.headers[j].Header2 + '</th><th class="col_2">' + object.headers[j].Header3 + '</th><th class="col_3">' + object.headers[j].Header4 + '</th><th class="col_4">' + object.headers[j].Header5 + "</th>");
        }
    });

    $.each(jsonData, function (index, object) {
        for (var j = 0; j < object.columns.length; j++) {
            $tbl.children("tbody").append("<tr><td>" + object.columns[j].PersonalLoans + "</td><td>" + object.columns[j].LoanAmount + "</td><td>" + object.columns[j].Fee + "</td><td>" + object.columns[j].APR + "</td><td>" + object.columns[j].Calculator + "</td></tr>");
        }
    });
    
    $.each(jsonData, function (index, object) {
        for (var j = 0; j < object.tableDetails.length; j++) {
            $("p.rateDisclosure").append(object.tableDetails[j].disclosure);
        }
    });
    
    $(document.body).append($tbl);
}

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

Discovering mutual friends on Facebook through the Graph API

I developed an application that displays mutual friends for users. To retrieve mutual friends on my node server, I have implemented the following code: var express = require('express'), FB = require('fb'), appFB = FB.extend({appId: & ...

Tips on removing the backslash character within a JSON key in Java

While I understand the importance of best practices, sometimes we have to prioritize meeting our customer's requirements, even if it means deviating from those practices. I'm sure many of you have been in a similar situation before and can relate ...

Vue 3 - Child Component Script Not Updating with Reactive Prop Changes

I am facing an issue where I am trying to pass a reactive data as a prop to a child component in Vue 3. The data updates correctly in the child component's template, but it does not reflect in the child component's script. In the parent component ...

"Retrieve and transfer image data from a web browser to Python's memory with the help

Is there a way to transfer images from a browser directly into Python memory without having to re-download them using urllib? The images are already loaded in the browser and have links associated with them. I want to avoid downloading them again and ins ...

ERROR: Expo TaskManager Notifications [TypeError: Attempting to call an undefined function (near '...Notifications.presentLocalNotificationAsync...')]

I'm currently trying to figure out how to send notifications whenever a task is triggered, but I keep encountering an error that I can't seem to fix. Here's the error message: TaskManager: Task "background-fetch" failed:, [TypeError: unde ...

Combining `.then` promises in axios - what's the best approach?

Imagine having a wrapper function for the axios function - something that needs to be used in every ajax query to keep the code DRY. Here is an example: import axios from "axios" import NProgress from "nprogress" const query = (url, options) => { ...

What is the best method to choose a dataset from this particular set of data?

{ "success" : true, "message" : "", "result" : [{ "PaymentUuid" : "554ec664-8842-4fe9-b491-06225becbd59", "Currency" : "BTC", "Amount" : 0.00156121, "Address" : "1K37yQZaGrPKNTZ5KNP792xw8f7XbXxetE", "Opened" : "2014- ...

How can I create a JSON object that contains a JSON array within it?

I am dealing with a many-to-many relationship structured as follows: Server version: 10.4.17-MariaDB table colors(id, name). table items(id, title....). table item_color(id, items_id, color_id). My SQL query looks like this: SELECT items.*, colors.name F ...

A guide on simulating HTTP methods in Jest when dealing with private methods

I'm grappling with how to simulate the following functionality. I need to simulate both methods: getAllBookInCategory, deleteBookInCategory The public method invokes private methods and I presume I don't need to test private methods, only callin ...

Would you like to know the process of retrieving a single, specific item from a database through a REST webservice using a

Hello, I am new to PHP and web services and I'm currently working on creating a simple REST web service. In my database, I have a table that contains coordinates of various cities. Below is the code I wrote to retrieve data in XML format: <?php ...

Tips for making my JavaScript form open a new window after submitting

Currently, the link opens in the same window when submitted. I would like it to open in a new window instead. This is the script in the head section: <script type="text/javascript"> function getURL(val){ base = 'http://www.domain.com/'; ...

Combining Vue.js with Laravel Blade

I've encountered an issue while trying to implement a Basic Vue script within my Laravel blade template. The error message I am getting reads: app.js:32753 [Vue warn]: Property or method "message" is not defined on the instance but referenc ...

Is it possible to generate multiple modal windows with similar designs but varying content?

I am facing a challenge with 140 link items that are supposed to trigger a modal window displaying a user profile for each link. The issue is that each user profile contains unique elements such as three images, a profile picture, text paragraph, and socia ...

Script malfunctioning following an AJAX request

My page consists of a header where all my javascript is located. Within the body of the page, there is a link that triggers an ajax http request using vanilla JavaScript (not jQuery). This request retrieves a PHP form and injects it onto my page. The PHP ...

Tips for preserving the status of a sidebar

As I work on developing my first web application, I am faced with a navigation challenge involving two menu options: Navbar Sidebar When using the navbar to navigate within my application, I tend to hide the sidebar. However, every ti ...

Checkbox selection causing Bootstrap accordion to collapse

Hey everyone, I'm currently working with Bootstrap 5 accordion and facing an issue where the input checkbox is triggering the "collapse" event of the accordion. I attempted to relocate the checkbox outside the scope of the accordion button but that so ...

Show dynamic HTML Dropdowns with nested JSON data

I've been racking my brains trying to implement this specific functionality in the UI using a combination of HTML5, Bootstrap, CSS, and JavaScript. My goal is to create dropdown menus in the UI by parsing JSON input data. Please Note: The keys withi ...

What status code would be most appropriate for invalid input in HTTP requests?

When processing input as json in my web service, what HTTP status code should be used for invalid input, specifically for PUT and POST requests? The commonly used response code for this scenario is "400 Bad Request", but are there better alternatives? I ...

divs adjust their size based on how many are placed in a single row

I'm in the process of developing an online editing tool, and I'm interested to know if it's feasible to adjust the size of a <div> based on the number of visible div elements. For instance, I have a row with three columns, each set at ...

Transforming the JSON POST data into a collection of objects

Using ASP.NET WEB-API 2.0 on the server side, I am sending a series of name value pairs as JSON data from the client side. How can I convert these into an array or list of objects containing both the name and value components in my WEB API controller? The ...