Converting JSON data into an HTML table

I'm struggling to convert a JSON object into an HTML table, but I can't seem to nail the format.

DESIRED TABLE FORMAT:

Last Year     This Year     Future Years
45423         36721         873409

CURRENT TABLE FORMAT:

Last Year     45423
This Year     36721
Future Years  873409

JSON DATA:

[{column_name:"Last Year", "column_data":45423},{column_name:"This Year", "column_data":36721},{column_name:"Future Years", "column_data":873409}]

HTML STRUCTURE:

<div class="panel-body">
    <div id="main-aged-debtors-bar" style="height: 250px"></div>
    <div>
        <table class="table table-hover" id="crpw_table">
            <thead>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
</div>

JAVASCRIPT CODE:

$.getJSON(url, jsonObject,
    function (data) {
        for (var i = 0; i < data.length; i++) {
            tr = $('<tr/>');
            tr.append("<td>" + data[i].column_name + "</td>");
            tr.append("<td>" + data[i].column_data + "</td>");
            $('#crpw_table').append(tr);
        }
    });  

Answer №1

There is not a significant difference

$.getJSON(apiLink, jsonObject,
    function (response) {
        tableRow1 = $('<tr/>');
        tableRow2 = $('<tr/>');
        for (var index = 0; index < response.length; index++) {
            tableRow1.append("<td>" + response[index].name + "</td>");
            tableRow2.append("<td>" + response[index].value + "</td>");
        }
        $('#data_table').append(tableRow1);
        $('#data_table').append(tableRow2);
    }
);  

Answer №2

$.getJSON(newUrl, newJsonObject,
    function (result) {
        var tableRow = $('<tr/>');
        for (var index = 0; index < result.length; index++) {
            tableRow.append("<td>" + result[index].name + "</td>");
        }
        $('#new_table').append(tableRow);
        tableRow = $('<tr/>');
        for (index = 0; index < result.length; index++) {
            tableRow.append("<td>" + result[index].data + "</td>");
        }
        $('#new_table').append(tableRow);
    }); 

Answer №3

Give it a shot,

$.getJSON(link, objectValues,
    function (result) {
        var row1 = $('<tr/>');
        var row2 = $('<tr/>');
        for (var index = 0; index < result.length; index++) {

            row1.append("<td>" + result[index].column_name + "</td>");
            row2.append("<td>" + result[index].column_data + "</td>");
            
        }
        $('#table_element').append(row1).append(row2);
}); 

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

Is it possible to modify @page directive(CSS) values from the code-behind(C#) or JavaScript?

Using the @page directive, you can define the printer margins for a page separately from regular CSS margins: <style type="text/css" media="print"> @page { size: auto; /* auto is the current printer page size */ margin ...

Steps to efficiently enumerate the array of parameters in the NextJS router:

In my NextJS application, I have implemented a catch all route that uses the following code: import { useRouter} from 'next/router' This code snippet retrieves all the parameters from the URL path: const { params = [] } = router.query When I co ...

How can I prevent anchors from performing any action when clicked in React?

My dilemma involves this HTML element: <a href onClick={() => fields.push()}>Add Email</a> The purpose of the href attribute is to apply Bootstrap styles for link styling (color, cursor). The issue arises when clicking on the element caus ...

JavaScript method for altering the values of variables

Having a small issue with my JavaScript function. Let me tell you what's going on: var intervalId = setInterval(function() { var value = parseInt($('#my_id').text(), 10); if(value > 0) { clearInterval(intervalId); console.log ...

"Is it possible to move the text on the canvas by dragging it to where you want it to be

Seeking help again after an unsuccessful attempt. How can I allow the user to add text to the canvas by dragging it to their desired location? For example, if they input text somewhere, it should appear on the canvas and then be draggable to any position ...

Ways to verify whether a vue instance is empty within a .vue file by utilizing the v-if directive

I am facing an issue with a for-loop in Vue that iterates through a media object using v-for to check if it contains any images. Everything is working correctly, but I want to display a div below the loop saying "There is no media" when the object is empty ...

Is there a method to run code in the parent class right after the child constructor is called in two ES6 Parent-Child classes?

For instance: class Parent { constructor() {} } class Child { constructor() { super(); someChildCode(); } } I need to run some additional code after the execution of someChildCode(). Although I could insert it directly there, the requirement is not to ...

What is the process for calculating the total sum of input values utilizing JavaScript?

My JavaScript skills are not perfect, and I'm struggling to calculate the total sum of values in the amount input boxes without refreshing the page. Can someone assist me with this challenge? Thank you. function Calculat ...

What is the best way to organize Node/Express routes based on their type into different files?

My /router/index.js file is becoming too cluttered, and I want to organize my routes by group (user routes, post routes, gear routes) into separate files within /router/routes/. Here's what I currently have set up: app.js var express = require(&apos ...

Using R to retrieve values from JSON lists

My knowledge in using R is limited and I need to create a script for a school project. I have a json file with nested lists, and my task is to extract values from two specific attributes. The challenge lies in the fact that these attributes are located i ...

Achieving a persistent footer at the bottom of the page within Material Angular's mat-sidenav-container while using the router-outlet

I am looking to keep my ngx-audio-player fixed at the bottom of the screen, similar to what you see on most music streaming websites. I currently have a structure with divs and various elements for dynamic content and playing music. The issue is that the ...

HTML counterpart to PHP's include for JavaScript components

I am searching for a Javascript alternative to a method I have been using in PHP. Specifically, I want to streamline the basic setup of my pages: <!DOCTYPE html> <html lang="en"> <head> <meta ch ...

Unable to include the variable "$localStorage"

While working on my method in app.js, I encountered the following error: Uncaught Error: [$injector:strictdi] function($rootScope, $q, $localStorage, $location) is not using explicit annotation and cannot be invoked in strict mode http://errors.angula ...

Ways to extract the coordinates for slices positioned around the circumference of a pie chart

Currently, I am working on designing a pie chart with D3 using d3.layout.pie(). The image resembles the one displayed below, but without the black dots. These dots were added manually in Photoshop to highlight an issue that I am facing. I am curious about ...

How can I use PHP and JavaScript to iterate through a <select> / <option> list and gather the values?

I am working on a project where I have a group of options within a selection dropdown and my goal is to utilize JavaScript to deselect all chosen values, gather them into a string, and then send it over to my PHP script. ...

Switch between playing and pausing the mp3 audio in the Next application by using the toggle

I am currently working on my website and I have been trying to add a button to the bottom of the page that can play or pause a song using useSound library. The song starts playing when I click it for the first time, however, I am facing difficulty in stopp ...

Parallax scrolling in all directions

Is there a resource available for learning how to program a website similar to the one at ? I am familiar with parallax but can't seem to find any examples that resemble what they have done on that site. ...

Preventing the "Return to Top Button" from showing up right before the footer

Reviewing my code, I have the following snippet: $(function() { // store scroll to top button in a variable var b = $('#back-top'); // Initially hide scroll top button b.hide(); // FadeIn or FadeOut scroll to top button on scroll event ...

Using jQuery and AJAX to prevent the default behavior of a link, initiate an AJAX request, and then navigate to the link afterwards

Attempting a seemingly 'simple' task has turned into quite the challenge for me. My goal is to have a user click a link, prevent the default action, execute an AJAX function, and then proceed to follow that link. So far, my attempts have only re ...

Converting JSON data to an array - dealing with both single and double quotes

I have a large JSON code consisting of 2,801,278 characters. I am trying to create an array from this JSON code in my PHP script, but I am facing issues due to the presence of quotes and double quotes which are causing errors. Here is a simple example that ...