How to load nested object array in DataTable

How to load nested object array in DataTable

boboxxboboxx Posts: 4Questions: 1Answers: 0

I have a json file that contains information and multiple recordsets (2 in this case). I'm trying to load them in individual datatable. I would like to load DMale DFemale in each a separate DataTable. My json file look looks like:

{
"event":[
   {
      "name":"test",
      "date":"Feb 11, 2018"
   }
],
"results":[
  {
     "Cat-D-Male":[
        {
         "Rank":"1",
         "Bib":"192",
         "First Name":"Kerry",
         "Last Name":"Reve",
         "Time":"01:01:28.445",
         "Gap":"",
         "Lap 1":"00:00:13.15",
         "Lap 2":"00:11:44.58",
         "Lap 3":"00:12:09.24",
         "Lap 4":"00:12:03.94",
         "Lap 5":"00:12:31.31",
         "Lap 6":"00:12:46.20"
        }
     ],
     "Cat-D-Female":[
        {
         "Rank":"1",
         "Bib":"178",
         "First Name":"Lisa",
         "Last Name":"Sax",
         "Time":"00:58:40.708",
         "Gap":"",
         "Lap 1":"00:00:14.89",
         "Lap 2":"00:11:49.55",
         "Lap 3":"00:11:29.52",
         "Lap 4":"00:11:21.15"
        },
        {
         "Rank":"2",
         "Bib":"325",
         "First Name":"Mellisa",
         "Last Name":"Sweet",
         "Time":"00:51:12.671",
         "Gap":"-1 Lap",
         "Lap 1":"00:00:17.52",
         "Lap 2":"00:12:56.86",
         "Lap 3":"00:12:23.24",
         "Lap 4":"00:12:54.41"
        }
     ]
  }
]
}

But I'm unable to extract DMale and DFemale to create the 2 DataTable. This is what I have so far:

<script>
  $( document ).ready( function( $ ) {
    $.ajax({
      type: "POST",
      url: 't4.json',
      cache: false,
      dataType: 'json',
      success: function(response) {
        $("#ResultsDiv").empty();
        $("#eventname").append(response.event[0].name);
        $("#eventdate").append(response.event[0].date);
        $("#eventlocation").append(response.event[0].location);
        console.log("1:" + response);
        var totalMessages = Object.keys(response.results[0]).length;
        console.log("2: Count= " + totalMessages);
        $.each(response.results[0], function(key, val) {
          console.log("3a:" + key);
          console.log("3b:" + val.length);
          console.log("3c:" + JSON.stringify(val));
          initiateTable(key, val);
        });
      }
    })

    function initiateTable(tableId, source) {
      $("#ResultsDiv").append('<table id="' + tableId + '" class="table table-striped table-condensed" cellspacing="0" width="100%"></table>');
      var table = $("#" + tableId).dataTable({
        "data": source,
        "bProcessing": true,
        "bPaginate": false,
        "bLengthChange": false,
        "bFilter": true,
        "bInfo": false,
        "bAutoWidth": true,
        "columnDefs": [{
          "targets": 'no-sort',
          "orderable": false
        }]
      });
    }
});
</script>

How can I pass each dataset to create a new DataTable and load the data and append it to the others tables in my div? I'm vey new at using JSon and DataTable, this is the fist time I use it.

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,455Questions: 1Answers: 10,465 Site admin

    It looks like you are already a good way along the road for this (feeding the result in with columns.data). The one thing I'm not clear on (and which I think is causing the difficulty) is that results is an array of objects, but you say that you want the two entries to be in different tables. Perhaps not having results as an array, but simply an object containing the two data points would be the way to do it?

    Allan

  • boboxxboboxx Posts: 4Questions: 1Answers: 0

    I'm looking for a way to load, event date, location and each dataset in it's own data table. But the problem I have is that I don't know how many dataset will be return or how many columns with name it will have each time. If there is a better way to format my json please let me know.

    If I go with 2 object won't I loos the name of my dataset?

    I'm trying to do like this:
    http://results.charetx2.com

    this is where I'm at now:
    http://results.charetx2.com/test/t5.html

  • kthorngrenkthorngren Posts: 21,303Questions: 26Answers: 4,947
    edited January 2018 Answer ✓

    I put together a simple example based on your data:
    http://live.datatables.net/piratuko/1/edit

    Its not a comprehensive example but hopefully will get you started. My example builds only one table. You would create a loop for all the tables based on the number of "results" you have. The first step is to append the table in HTML. I would make the table id the same as the "results" name, ie, "DMale"

    Next is to build the columns. Each column should use columns.data and columns.title. Using columns.title will build the table headings so you don't have to. Not sure how you are generating the column names but here are a few comments that might help:

    • Don't put each column name in its own array. Just build an array of names or an array of objects if you do the next step.
    • Maybe your server script can build the data and title objects and map them accordingly. Otherwise they will need to be mapped as in the example script.
    • Only return the column names that exist in the data. Or add a check in the Javascript to not add the column if it doesn't exist in the data, "Lap 7" in the example. I simply commented this out.

    Looks like the only data manipulation needed is to combine the "First Name" and "Last Name" columns into a data object "Name". You can do this in JS as in my example or maybe your server script can do this. Your "results" object is an array containing one object. Maybe you can remove this outer array and just have "results" be the object.

    In general its better to have the server script return the data as close to what is needed as possible rather than manipulating it in JS. This way changes are only needed in one place.

    HTH,
    Kevin

  • boboxxboboxx Posts: 4Questions: 1Answers: 0

    That helped out a lot, I rearranged my json and have a working model, now the only issue I have is i'm unable to set the width of my columns

    Here is what I have:
    http://live.datatables.net/semulese/2/edit

  • boboxxboboxx Posts: 4Questions: 1Answers: 0
    edited January 2018

    thanks guys here is the final code if anyone ever needs it:

    http://live.datatables.net/semulese/4/edit

This discussion has been closed.