How to support dynamic columns?

How to support dynamic columns?

wlin98004wlin98004 Posts: 7Questions: 2Answers: 0

I have data from a pivot table. The number of columns return is not fixed. Right now, I am manually specifying columns to be displayed. Is there a way dataTable can automatically include columns without specifying them?

$('#answer_table').DataTable( {
data: data[314635].data,
columns: [
{ "data": "P_Rank", title: "Prev<br>Rank" },
{ "data": "C_Rank", title: "Current<br>Rank" },
{ "data": "SERVICE", title: "SERVICE" },
{ "data": "SCENARIO", title: "SCENARIO" },
{ "data": "QUERY_RAWQUERY", title: "Query1"},
{ "data": "QUERY_RAWQUERY", title: "Query2"},
{ "data": "QUERY_RAWQUERY", title: "Query3"},
{ "data": "CombinedRank", title: "Rank<br>Diff" }
]
} );

Answers

  • loloskiloloski Posts: 46Questions: 5Answers: 1

    try

    columns: loader()

    function loader() {

    return [ { "data": "P_Rank", title: "Prev<br>Rank" }, { "data": "C_Rank", title: "Current<br>Rank" }, { "data": "SERVICE", title: "SERVICE" }, { "data": "SCENARIO", title: "SCENARIO" }, { "data": "QUERY_RAWQUERY", title: "Query1"}, { "data": "QUERY_RAWQUERY", title: "Query2"}, { "data": "QUERY_RAWQUERY", title: "Query3"}, { "data": "CombinedRank", title: "Rank<br>Diff" } ] } );

    }

    if this works then wrapped $.ajax request and ask your backend about this dynamic tables of yours but the response structure should look like the array I hope you got the idea.

  • wlin98004wlin98004 Posts: 7Questions: 2Answers: 0

    Thank you for the help. It worked. For those who are interested, here is what I did.

      // show answer hits by market
      $('#market_table').DataTable( {
        data: data[339437].data,
        columns: column_loader(data[339437].columns),
      } );
    
    
    function column_loader(columns) {
      
      var columns2 = [];
      
      // go through all columns and add them to the table one by one.
      $.each(columns, function(index, value) {
          columns2[columns2.length] = {data: value, title: value};
      });
      
      return columns2;
    }
    
  • loloskiloloski Posts: 46Questions: 5Answers: 1

    glad it was sorted then...

This discussion has been closed.