Home > Enterprise >  jQuery - Dynamic DataTable - Data JSON
jQuery - Dynamic DataTable - Data JSON

Time:12-11

I want to create a DataTable with Dynamic Columns And Data.
My html code:

<body>
    <table id="example" >
    </table>
</body>

My data.json:

{
    "Category": {
        "0": "Bags",
        "1": "Shoes",
        "2": "School",
        "3": "Video-Games",
        "4": "PC-Games"
    },
    "Price": {
        "0": 10,
        "1": 20,
        "2": 30,
        "3": 40,
        "4": 50
    }
}

In this point, i want Category and Price to be the columns.

My js code is:

$(document).ready(function name(params) {
    $.ajax({
        url: "data.json",
        method: 'get',
        dataType: 'json',
        success: function (response) {
            var columns = Object.keys(response).map(function (key) {
                return { title: key };
            });

            $('#example').DataTable({
                data: Object.values(response),
                columns: columns
            });
        },
        error: (error) => {
            console.log(JSON.stringify(error));
        }
    });
});

I want the below result
https://i.stack.imgur.com/UkHuu.png

But i recieve this:
enter image description here

CodePudding user response:

The documentation suggests a slightly different data and columns formats.
for each column, you have to specify the data to use and its title
And each row has to be an object keyed by the column data it was assigned.

I admit that DataTables documentation is a bit unintuitive to navigate... But it is extensively complete.

Below is the code you should have in the Ajax success callback.

const data = {
  "Category": {
    "0": "Bags",
    "1": "Shoes",
    "2": "School",
    "3": "Video-Games",
    "4": "PC-Games"
  },
  "Price": {
    "0": 10,
    "1": 20,
    "2": 30,
    "3": 40,
    "4": 50
  }
}

const columnKeys = Object.keys(data)
const columns = columnKeys.map((column) => ({title: column, data: column}))
const rowKeys = Object.keys(data[columnKeys[0]])
const rows = rowKeys.map((rowKey) => {
  const row = {}
  columnKeys.forEach((columnKey) => row[columnKey] = data[[columnKey]][rowKey])
  
  return row
})

//console.log(columnKeys)
console.log(columns)
//console.log(rowKeys)
console.log(JSON.stringify(rows))

$('#example').DataTable({
  data: rows,
  columns: columns
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js"></script>

<body>
  <table id="example" >
  </table>
</body>

  • Related