7

I have the below code for displaying array of objects having property and a value in a data table. But here the column headers are hardcoded as seen in my below html code. How can I make it dynamic based on the input dataset?

 var dataSet = [{
  "Latitude": 18.00,
  "Longitude": 23.00,
  "Name": "Pune"
}, {
  "Latitude": 14.00,
  "Longitude": 24.00,
  "Name": "Mumbai"
}, {
  "Latitude": 34.004654,
  "Longitude": -4.005465,
  "Name": "Delhi"
},{
  "Latitude": 23.004564,
  "Longitude": 23.007897,
  "Name": "Jaipur"
}];
$(document).ready(function() {
    $('#example').DataTable( {
        data: dataSet,
        "columns": [
            { "data": "Name" ,"title":"Custom Name"},
            { "data": "Latitude" },
            { "data": "Longitude" },

        ]
    } );
} );




<table id="example" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Latitude</th>
                <th>Longitude</th>

            </tr>
        </thead>

    </table>

2 Answers 2

14

Assuming the structure of the objects in the dataSet does not change, you could use the first object to build the json object external to the DataTable declaration. If the objects are not of a consistent structure, then you can tweak the logic inside the $.each structure to handle that.

Here's a quick hack:

var dataSet = [{
  "Latitude": 18.00,
  "Longitude": 23.00,
  "Name": "Pune"
}, {
  "Latitude": 14.00,
  "Longitude": 24.00,
  "Name": "Mumbai"
}, {
  "Latitude": 34.004654,
  "Longitude": -4.005465,
  "Name": "Delhi"
}, {
  "Latitude": 23.004564,
  "Longitude": 23.007897,
  "Name": "Jaipur"
}];

var my_columns = [];

$.each( dataSet[0], function( key, value ) {
        var my_item = {};
        my_item.data = key;
        my_item.title = key;
        my_columns.push(my_item);
});

$(document).ready(function() {
  $('#example').DataTable({
    data: dataSet,
    "columns": my_columns
  });
});

You should also consider removing all the static table content in your HTML like this

<table id="example" class="display" cellspacing="0" width="100%"></table>

Here's the jsFiddle https://jsfiddle.net/z4t1po8o/18/

Have fun.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, that helped. I do have inconsistent data structure..so what do you mean by tweaking the logic inside the $.each structure to handle that ??
Sak, The $.each block loops through the first item and builds the object structure for my_columns, which is used to initialize the DataTable in document.ready. If the first item does not represent the full definition of the table, then the 0 index in dataSet[0] needs to change to point to the item that does. Alternatively, some other manual massaging of the object is required to make sure the my_columns object accurately represents the columns in the table.
If wraning with parameter you can use add more option: "columnDefs": [{ "defaultContent": "-", "targets": "_all" }]
1

Here is the answer to fetch it from external json

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="script.js"></script>
<div><table id="example"></div>

script.js

jQuery( document ).ready( function( $ ) {
        // Code using $ as usual goes here.

        $.ajax( {
            url: '1.json',
            dataType: "json",
            "success": function ( json ) {
              var tables = $("#example").DataTable({               
                dom : 'l<"#add">frtip',
                "language": {
    "paginate": {
      "previous": "<&nbsp;Previous",
      "next": "next&nbsp;>"
    }
  },
                "columnDefs": [ {
    "targets": 2,
    "createdCell": function (td, cellData, rowData, row, col) {
      if (( cellData > 3 ) && ( cellData < 30 )){
        $(td).css('color', 'green')
      }
      else
           if (( cellData > 31 ) && ( cellData < 50 )){
        $(td).css('color', 'orange')
      }
      else
           if (( cellData > 51 ) && ( cellData < 100 )){
        $(td).css('color', 'red')
      }
    }
  } ],
                "ajax": {
                    "url": "1.json",
                    "type": "POST",
                    "datatype": "json"
                },
                "columns": json.columns
            });
            $('<label/>').text('Search Column:').appendTo('#add')
$select = $('<select/>').appendTo('#add')
$('<option/>').val('0').text('Index').appendTo($select);
$('<option/>').val('1').text('Name').appendTo($select);
$('<option/>').val('2').text('Age').appendTo($select);
$('<option/>').val('2').text('Image').appendTo($select);
$('input[type="search"]').on( 'keyup change recheck', function () {
  var searchValue = $(this).val();
  var columnSearch = $select.val();

  $('#example').DataTable().columns().every(function() {
    //alert('hi');
        this.search('');
    }); 

  if(columnSearch == 'All'){
    tables.search(searchValue).draw();
  } else {
    tables.columns(columnSearch).search(searchValue).draw();
  }
 });
 $select.on('change', function() {
 $('#example').DataTable().search('').draw();
 $('input[type="search"]').trigger('recheck');
 });
            },

        } );
    });

1.json

{
   "data":[
      {
         "Index": 4,
         "Name": "Bob",
         "Age": 7,
         "Image": "None"
      },
      {
         "Index": 2,
         "Name": "Timmy",
         "Age": 4,
         "Image": "None"
      },
      {
         "Index": 3,
         "Name": "Heather",
         "Age": 55,
         "Image": "ddd"
      },
      {
         "Index": 5,
         "Name": "Sally",
         "Age": 22,
         "Image": "None"
      }
   ],
    "columns": [
        { "title": "Index", "data" : "Index" },
        { "title": "Name",  "data": "Name" },
        { "title": "Age", "data": "Age" },
        { "title": "Image", "data": "Image" }
    ]
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.