Versatile dataTable designed to seamlessly integrate with various data structures

My task is to develop an ajax dataTable that can handle a variety of data sources with different column names and data types. The challenge lies in the fact that I cannot predefine the column names or data types when coding the dataTable, as each data source varies. However, all data sources share a common row_id identity column which is used to retrieve individual records.

I have made numerous attempts but have not achieved success yet.

Examples of tables in the database:

Table A: https://i.sstatic.net/hiVhC.png

Table B: https://i.sstatic.net/PqY5H.png

Details HTML:

<table id="tblDetails" class="tbl"></table>

Details Controller:

        public ActionResult GetDetails(int row_id, string table)
        {            
            DataTable dt = new DataTable();
            dt = helper.GetDetails(row_id, table);
            JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row;
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    row = new Dictionary<string, object>();
                    foreach (DataColumn col in dt.Columns)
                    {
                        row.Add(col.ColumnName, dr[col]);
                    }
                    rows.Add(row);
                }
            }
            return Json(rows, JsonRequestBehavior.AllowGet);
        }

js:

    var objParams = { 'table': table, 'row_id': row_id };
    $.ajax({
        url: $("#GetDetailsUrl").val(),
        method: "post",
        data: JSON.stringify(objParams),
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (data) {            
            var key = Object.keys(data)[0];
            var value = data[key];
            Object.keys(data).forEach(function (key) {
                console.log(key, value);
                // Everything works fine until the next line of code
                var row = '<tr><td>' + key + '</td><td> ' + value + '</td></tr>';
                $('#tblDetails').append(row);
            })
         }
});

When querying tableB & row_id = 2, the `console.log(key, value);' produces the expected output: https://i.sstatic.net/PAWCm.png

However,

var row = '<tr><td>' + key + '</td><td> ' + value + '</td></tr>';
fails. It results in key = 0 and value = undefined.

What steps should I take to fix this issue and make key & value work in var row just like it does when displayed in the console?

Answer №1

To process each key item within every row object, the Array.forEach() method must be utilized. Below is a snippet where I've emulated your table examples in JSON format. A function has been created that takes the table node and table data as parameters. It dynamically generates the table columns regardless of the number. Each line within the function is thoroughly annotated for better understanding.

const tableDataA = [{
    row_id: 1,
    customer: `Company 1`,
    name: `Smith`
  },
  {
    row_id: 2,
    customer: `Company 2`,
    name: `Jones`
  },
];

const tableDataB = [{
    row_id: 1,
    one: 1,
    two: 2,
    canBeAnything: `XyZ`
  },
  {
    row_id: 1,
    one: 5,
    two: 62,
    canBeAnything: `foo`
  },
];

const tblDetailsA = document.querySelector(`#tblDetails-a`);
const tblDetailsB = document.querySelector(`#tblDetails-b`);

createTable(tblDetailsA, tableDataA);
createTable(tblDetailsB, tableDataB);

function createTable(tableNode, tableDataArray) {
  // Create the thead element
  const thead = document.createElement('thead');
  // Create the tr for the header
  const headerRow = document.createElement('tr');
  // Get the title for each column by getting 
  // the keys of the first object in the array.
  const keys = Object.keys(tableDataArray[0]);
  // Iterate through each of the keys 
  keys.forEach(key => {
    // Create the th element for the column title
    const th = document.createElement('th');
    // Assign the inner text of the th to the value of the key
    th.innerText = key;
    // Append the the element to the header row
    headerRow.append(th);
  });
  // Append the header row to the thead element
  thead.append(headerRow);
  // Append the thead element to the table
  tableNode.append(thead);
  
  // Create the tbody element
  const tbody = document.createElement('tbody');
  // Iterate though each object of the data array
  tableDataArray.forEach(row => {
    // Create the tr element for the row
    const tr = document.createElement('tr');
    // Iterate through each key in the row Object
    Object.keys(row).forEach(col => {
      // Create the td element for the table data
      const td = document.createElement('td');
      // Assign the inner text of the td
      td.innerText = row[col];
      // Add the td to the row
      tr.append(td);
    });
    // add the row to the tbody
    tbody.append(tr);
  });
  // add the tbody to the table  
  tableNode.append(tbody);
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9ffdf0f0ebecebedfeefdfaab1adb1ac">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

<div class="container">
  <h5 class="text-center">Table A</h5>
  <table id="tblDetails-a" class="table"></table>
</div>
<div class="container">
  <h5 class="text-center">Table B</h5>
  <table id="tblDetails-b" class="table"></table>
</div>

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

Applying Media Queries Based on Element Height

Situation: In my scenario, there is an image with two buttons below it, all of which share the same width. Issue: When the viewport is too wide horizontally, the buttons are not visible without scrolling down. This poses a challenge for tablets and small ...

Malfunction in triggering events within an Ajax Magnific popup feature

I'm trying to load a page within a magnific popup using ajax: $("#operator").magnificPopup({ delegate: 'a.edit', mainClass: 'mfp-fade', closeBtnInside: true, removalDelay: 300, closeOnContentClick: false, t ...

The background image is not appearing on the div as expected

I've been attempting to create a div and set a background image for it using jQuery, but I seem to be facing issues. When I try setting the background color to white, it works fine. Here's the code snippet: function appendToDom(poster) { ...

Selecting any of the bar chart labels will reveal just a two-day timeframe

My bar chart is behaving strangely - when I click on all labels, it only shows two days instead of updating as expected. I suspect it may be due to a bad implementation involving parsing. Can anyone provide assistance? I have created a minimum example on ...

The React Apexchart fails to correctly adjust its height based on its parent container when set to 100%

Currently, I am working with react-apexcharts and facing an issue where I am trying to set the height of the chart to be 100% of its parent element. However, instead of taking the height from its parent, it is only showing a minimum height of 445px. Even a ...

Create a custom Android home screen widget using JavaScript or another programming language

I have a project in mind to create an Android App and include a home-screen widget. While I know it can be done with Native Android, my preference is to use JavaScript for development. Would anyone happen to know of any other solutions that allow the use ...

Tips for transferring information from a controller to a directive in AngularJS using AJAX requests

I want to pass data to a directive once the call is successful. Below is the ajax call from my controller: $scope.items ={ avatar: "" }; $scope.addComment = function(segment) { commentFactory.saveComment($scope.form.comment,segment,0, ...

Turn off escape option when PointerLockControls are in use

Is there a way to prevent the ESCAPE option from being activated (when using PointerLockControls and ThreeJS) by pressing the escape key on the keyboard? I have a different function in mind for this key in my project! Appreciate any assistance in advance ...

Updating the functionality of one-page scrolling - changing to overlap instead of sliding upwards

Hello, I am currently utilizing a JavaScript library to create a website with full page scrolling. If you want to know about the library, check out this link: For those interested, here is an example of my work on jsfiddle: http://jsfiddle.net/aLjLjxux/ ...

React - output from forEach() function is not defined

I am facing a challenge in rendering prop values from a nested object. There are two issues that I'm encountering: 1. The JSX code line (with variables) is not showing up in the browser 2. When I console log the variables with .forEach() methods, th ...

I'm having trouble accessing the outcome from within the function

Having trouble getting the result to return inside a function for my basic rock paper scissors game. I've tried everything, including console logging the compare and putting it inside a variable. Strange enough, console.log(compare) is returning und ...

Angular Material Sidenav fails to cover the entire screen while scrolling

https://i.stack.imgur.com/32kfE.png When scrolling, the Sidenav is not expanding to take up 100% of the screen and it continues to scroll along with the page content. <div layout="column"> <section layout="row" flex> <!-- siden ...

Every checkbox on the Angular 6 platform has been chosen

In my model class named processAnexOne.ts, I have the following structure: export class ProcessAnexOne { documentList: string; } Within the component class, I have initialized an instance as follows: export class ProcessAnexOneComponent implements O ...

Generating hierarchical structures from div elements

Looking for guidance on how to parse a HTML page like the one below and create a hierarchical Javascript object or JSON. Any assistance would be much appreciated. <div class="t"> <div> <div class="c"> <input t ...

What reasons could lead to useSWR returning undefined even when fallbackData is provided?

In my Next.js application, I'm utilizing useSWR to fetch data on the client-side from an external API based on a specified language query parameter. To ensure the page loads initially, I retrieve data in a default language in getStaticProps and set it ...

Tips for wrapping a div around its floated children

I'm currently developing a website for an online shopping cart and working on making the search results responsive. I am aiming to display as many items as possible across the screen (usually 3) when viewed on any device with a resolution lower than t ...

Dealing with a SyntaxError while using JSON.parse due to having multiple values assigned to

Consider this as an example of JSON data: const jsonData = { "Level1": [ { "Level2": [ { "Level3": [ { "body": "AAAAA" }, { ...

Leveraging NestJs Libraries within Your Nx Monorepo Main Application

I am currently part of a collaborative Nx monorepo workspace. The setup of the workspace looks something like this: https://i.stack.imgur.com/zenPw.png Within the structure, the api functions as a NestJS application while the data-access-scripts-execute ...

[AWS Lambda SDK] - Executing Lambda Function - Processing Payload Response as Unit8Array - Conversion to String

Currently, I am utilizing the npm package @aws-sdk/client-lambda to invoke Lambdas. In my setup, I have two Lambdas - Lambda A and Lambda B, with Lambda A responsible for invoking Lambda B. The invocation of Lambda B from Lambda A is done through the foll ...

What is the best way to extract the text from a class only when it is nested within a particular header tag?

const request = require ('request'); const cheerio = require('cheerio'); const fs = require ('fs'); request("http://kathmandupost.ekantipur.com/news/2018-08-31/bimstec-summit-multilateral-meet-underway.html", (error, response ...