Home > Blockchain >  Build jQuery datatable using array of objects
Build jQuery datatable using array of objects

Time:10-21

I am trying to create and populate a jQuery datatable using an array of objects where each objct has two properties: HR and TXN_COUNT. It represents number of transaction by the hour and looks something like:

HR  TXN_COUNT
00  4591
01  2402
...
08  2129

I need content of first column as datatable column headers and second column as data, so that I would end up with:

 00    01    ...   08
4591  2402        2129

Can't get it to work.

I have tried this:

<div id="divGrid" style="clear: both">
    <table id="txnTable" class="table table-striped table-bordered table-hover display responsive compact divGrid " style="width: 98%;">
    </table>
</div>
...

$(document).ready(function () {
    ...
    populateTable();
});

function populateTable() {
    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        url: "../WebService/ABC.asmx/GetTransactionCountByDay",
        cache: false,
        data: JSON.stringify({ SelDate: selDate, LogType: -1 }),
    }).done(function (result) {debugger
        var jResult = JSON.parse(result.d);
        //columnNames = jResult.map(a => a.HR);

        // Stupid IE version, since it doesn't understand '=>' !
        columnNames = jResult.map(function (a) { return a.HR; });
        tblData = jResult.map(function (a) { return a.TXN_COUNT; });

        $('#txnTable').DataTable({
            destroy: true,
            processing: true,
            serverSide: true,
            data: tblData,
            columns: columnNames
        });
    })
}

When I run this, I see correct values in columnNames and tblData arrays. However, I get jquery error (Invalid operand to 'in': Object expected) in function "isArrayLike( obj )" where object is the string "00" (the first HR value). When I continue the process, I just see my "wait" spinner spinning and nothing displayed. This happens when it is creating the datatable.

Update

Adding this piece of code just before creating datatable at least displays the table headers. Seems "columns" property of datatable expects object and I was passing string (e.g. "00").

for (var i in columnNames) {debugger
    columns.push({
        data: columnNames[i],
        title: columnNames[i]
    });
}

and then set the "column" property to columns instead of columnNames. Now I get an error in datatable's js (Unable to set property 'data' of undefined or null reference)

CodePudding user response:

Here is how I would approach this, given the requirement to pivot the source data into a single row for the DataTable:

Starting assumptions:

(1) I will ignore the serverSide: true option, since it's not clear if it is required, and it is not relevant to how the source JSON data needs to be transformed.

(2) Since this is about transforming the source data, I will also ignore the data being sent to the server with each request.

(3) I will assume the URL delivers the following JSON:

[
  {
    "DT": "2021-10-19",
    "HR": "00",
    "TXN_COUNT": 138
  },
  {
    "DT": "2021-10-19",
    "HR": "01",
    "TXN_COUNT": 235
  },
  {
    "DT": "2021-10-19",
    "HR": "02",
    "TXN_COUNT": 111
  },
  {
    "DT": "2021-10-19",
    "HR": "03",
    "TXN_COUNT": 120
  },
  {
    "DT": "2021-10-19",
    "HR": "04",
    "TXN_COUNT": 120
  },
  {
    "DT": "2021-10-19",
    "HR": "05",
    "TXN_COUNT": 120
  },
  {
    "DT": "2021-10-19",
    "HR": "06",
    "TXN_COUNT": 318
  },
  {
    "DT": "2021-10-19",
    "HR": "07",
    "TXN_COUNT": 505
  },
  {
    "DT": "2021-10-19",
    "HR": "08",
    "TXN_COUNT": 294
  }
]

This is based on what you provided in your notes, but with some clean-up to make it valid JSON.

Then I would use this JSON as follows:

$(document).ready(function () {
    populateTable();
});

function populateTable() {
    $.ajax({
        type: "POST",
        method: "POST",
        // my test URL:
        url: "http://localhost:7000/GetTransactionCountByDay",
        cache: false
    }).done(function (result) {
        var columnNames = [];
        var tblData = [];
        result.forEach(item => {
          // build an object containing the column names:
          columnNames.push( { title: item.HR } );
          // build an array containing the one row data
          tblData.push( item.TXN_COUNT );
        });
        
        $('#txnTable').DataTable({
            // note how the data is wrapped in another array,
            // because the data needs to be an array of arrays
            // for DataTables to process it (or an array of objects):
            data: [ tblData ],
            columns: columnNames
        });
    })
}

The end result looks like this (not all columns are shown in the screenshot):

enter image description here

  • Related