How to render the columns or columnDefs for a dynamic data source?

How to render the columns or columnDefs for a dynamic data source?

CuroDeveloperCuroDeveloper Posts: 8Questions: 2Answers: 0

Hi, I have been searching the forum on how to render the columns or columnDef of a datable when the data source is dynamically generated with [n] columns. In other words, the data source can be 1 column or 4 columns or [n] columns. Below is an example of my dataSet with 2 columns. The number of columns is determined by how many items are selected by the end-user. So it can range from 1 to [n].

datasSet = [
{
    "NAME": "FormLetterFTP_URL",
    "CAN_DEV": "transfer.datagroup.ca"
  },
  {
    "NAME": "FormLetterFTPAdAstra_URL",
    "CAN_DEV": "ftp://ftp.xyz.com"
  },
  {
    "NAME": "FormLetterFTPAdAstraDownloadPath",
    "CAN_DEV": "/from_HC/Test_CAN_PRE/"
  },
]

<script>
        var dataSet = <%= JsonConfigData %>
            $('#table_id').DataTable({
                data: dataSet,

               How to define columns [ ..... here.....]?

            });
 </script>

This question has an accepted answers - jump to answer

Answers

  • colincolin Posts: 15,118Questions: 1Answers: 2,583
    Answer ✓

    Hi @CuroDeveloper ,

    You can use variables as part of the column definition, so you could build up the variable first, and then pass it into the initialisation, something like:

                var myColumns = []; // do some loop to build up that array
                $('#table_id').DataTable({
                    data: dataSet,
                    columns: myColumns
                });
    

    Hope that helps,

    Cheers,

    Colin

  • CuroDeveloperCuroDeveloper Posts: 8Questions: 2Answers: 0

    Colin,

    Thank you. It worked

    [
    {"Data":"NAME"},
    {"Data":"CAN_DEV"},
    {"Data":"CAN_PRE"},
    {"Data":"CAN_PROD"},
    {"Data":"CAN_PROD_QA"}
    ] 
    
  • CuroDeveloperCuroDeveloper Posts: 8Questions: 2Answers: 0

    Final result

     <script>
            var dataSet = <%= JsonConfigData %>
            var dataColumns = <%= JsonDataColumns %>
    
                $('#table_id').DataTable({
                    "scrollY": 450,
                    "scrollX": true,
                    "paging": false,
    
                    data: dataSet,
                    columns: dataColumns
                });
        </script>
    
This discussion has been closed.