Home > front end >  Populate JQuery DataTable With JavaScript Array
Populate JQuery DataTable With JavaScript Array

Time:07-11

I've got what I Think is an array of objects like this console.log shows

Array(39) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
0: Object { Name: "Jason", Grade: 12 }

What code should I use to format it so that the jQuery datatable will let me set this as the source?

https://datatables.net/

I tried to do this, but it gives me an error:

    $.myjQuery = function(testData) {
      $('#example').DataTable({
        data: testData,
        columns: [
          { title: 'Name' },
          { title: 'Grade' },
        ],
      });

CodePudding user response:

Looking at the documentation

and Forums

You need

columns: [
  { data: 'Name' },
  { data: 'Grade' },
]

using your data

const dataSet = [
 { Name: "Jason", Grade: 12 },
 { Name: "Mike", Grade: 11 },
 { Name: "Freddie", Grade: 10 }]
 
$(function () {
  $('#example').DataTable({
    data: dataSet,
    columns: [
      { data: 'Name' },
      { data: 'Grade' },
    ],
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
<link src="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css" />

<table id="example"  width="100%"></table>

Or THIS when converting to nested arrays

const yourArray = [
 { Name: "Jason", Grade: 12 },
 { Name: "Mike", Grade: 11 },
 { Name: "Freddie", Grade: 10 }]
 
 const dataSet = yourArray.map(({Name,Grade}) => [Name,Grade])
$(function () {
  $('#example').DataTable({
    data: dataSet,
    columns: [
      { title: 'Name' },
      { title: 'Grade' },
    ],
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
<link src="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css" />

<table id="example"  width="100%"></table>

  • Related