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:

Table B:

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:

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

What is the best way to transform a PredictResponse into a JSON format?

I'm currently working on accessing a VertexAI project using both a React frontend and a Python backend. I recently asked for help with sending requests to VertexAI from Node, as detailed here. While in the Python approach I can successfully make and ...

There is a lack of definition for an HTML form element in JavaScript

Encountering an issue with a HTML form that has 4 text inputs, where submitting it to a Javascript function results in the first 3 inputs working correctly, but the fourth being undefined. Highlighted code snippet: The HTML section: <form action="inse ...

Is it beneficial to utilize jQuery ahead of the script inclusions?

While working on a PHP project, I encountered a situation where some parts of the code were implemented by others. All JavaScript scripts are loaded in a file called footer, which indicates the end of the HTML content. This presents a challenge when tryi ...

How can I ensure that the size of the Dropdown Menu Item matches its parent in both Bootstrap and CSS styles?

I am working on a navigation bar that has a dropdown menu which appears on hover. I want the size of the dropdown menu items to match the size of the parent element. Here is an image for reference: https://i.stack.imgur.com/oNGmZ.png Currently, the "One ...

"Effortlessly move elements with HTML5 drag and drop functionality from either direction

I'm working on an application that requires Html5 Drag and Drop functionality, which is currently functioning well. However, in the app, there may be instances where a dropped item is no longer needed and I want to allow users to re-drag and drop it b ...

Unable to retrieve JSON data using CURL in PHP

I thought I had a good handle on PHP/curl, but now I'm stuck. I can easily fetch [GET] , but when I try to get JSON from [GET] , it's not working. It works fine in the browser and even in POSTMAN with all security options disabled. Here's ...

Identifying modifications in json file within Ansible can be problematic when using jq due to variations in indentation, resulting in the file always being marked as

Looking to use Ansible to update a specific string in a JSON file? Unfortunately, Ansible lacks a module similar to xml for handling JSON files. As a workaround, I'm utilizing the jq command-line tool. Since restarting the application is time-consumin ...

Tips for identifying selected rows in Material UI DataGrid

Currently, I am in the process of developing a website using React along with Material UI. My main focus right now is to identify which rows are currently selected in my DataGrid. To achieve this, I want to populate an array with the selected rows using t ...

How to successfully extract and understand JSON data in Angular that has been delivered from a Spring controller

I am facing a unique challenge while trying to utilize JSON data obtained from a Spring API to populate a list in Angular. Within the datasets-list.component.ts file, I have the following code: import { Component, OnInit } from '@angular/core'; i ...

Mastering the art of maximizing efficiency with the Jquery Chosen Plugin

Currently, I'm facing an issue with the jQuery chosen plugin due to my large datasets causing the select box to hang and slow down. Below is my implementation of the plugin: var request = $.ajax({ method: "POST", url: "ajaxRequest.php", d ...

Retrieving the IDs of all socket connections in a Node.js Socket.IO array

I currently have a complex program utilizing socketio 0.9 where I am storing all the sockets id in arrays like so: var clients = {}; To uniquely identify and store my sockets, I assign them a serial and then set the 'socket' key with its actual ...

Trigger a Redux action with the following action as the payload in order to display a Material UI snackbar or dialog

Currently, my project involves using React along with Redux and Material UI to develop a web application. The web app consists of numerous pages and components. It is common practice to have a snackbar or dialog interact directly with the user's actio ...

How to retrieve 'data' attributes from an object that was dynamically loaded?

I'm currently facing an issue with accessing the data attributes of a dynamically loaded file using AJAX. For instance, I load a file containing: <div id="blah" class="hello" data-something="or_other" /> Then, I use jQuery to access the data: ...

Having trouble parsing asynchronous script with cheerio parser

Utilizing cheerio for web crawling poses a challenge when encountering websites with asynchronous scripts. When attempting to extract all the scripts from such websites, they are often missed in the process. Here is an example of the code I am currently us ...

The variable _spPageContextInfo has not been defined, resulting in a ReferenceError

The code in my JavaScript file looks like this: var configNews = { url:_spPageContextInfo.webAbsoluteUrl, newsLibrary: 'DEMONews', listId: '' }; // Attempting to retrieve the List ID $.ajax({ url: configNews.url + "/_a ...

Commitments do not come with a collections feature

Struggling to implement the collection method, it seems that I can't directly use db.collection as db is calling connectDB, which returns conn, my mongoURI, as a promise. How can I modify this setup to effectively utilize the collection method and sen ...

Unable to scroll to top using div scrollTop() function

Here's the fiddle I mentioned: http://jsfiddle.net/TLkmK/ <div class="test" style="height:100px;width:70px;overflow:auto"> Some text here that needs scrolling. </div> alert($('.test').scrollTop()); Feel free to scroll down ...

Creating a Webgrid in MVC and integrating it with a custom class in AngularJS

Hey there, I'm a beginner when it comes to AngularJS and I'm looking to bind the webgrid within the method of AngularJS. $scope.SaveDetails = function () { debugger; var UserID = '@Session["ID"]'; ...

deployJava.js injects a new <embed> element into the header section of the webpage

I've ran into an issue with the Java applets on my website. I included the deployJava.js load tag in the head section of the page, but when I look at the resulting HTML in Chrome debugger, this script seems to be breaking my head content and starting ...

What ways can I leverage JavaScript to convert a provided array into multiple different arrays?

I am in need of a function that meets the following criteria: Given the dimensions of an array, return all possible combination arrays based on the given numbers. The length of the given array should be equal to the length of the array returned. The size ...