Column names don't match the data -- how do I rename and dynamically create column names?

Column names don't match the data -- how do I rename and dynamically create column names?

rldean1rldean1 Posts: 141Questions: 66Answers: 1
edited February 2018 in Free community support

I can populate a table! In SQL, I create a JSON string, and then in JS, I parse that string into a JSON object that looks like this:

[{"Effective Date":"2000-06-30","Schedule":"UR-FUPA","Description":"FUPA Class IV","Calculated":"No"}]

In HTML, I specify Column Names that match what's in the JSON object: "Effective Date", Schedule", "Description", and "Calculated". In JS, I match up the column names:

$("#tblSomeTable").DataTable({
"data": obj,
"columns": [
{ "data": "Effective Date" },
{ "data": "Schedule" },
{ "data": "Description" },
{ "data": "Calculated" },
],
});

So, here is my main question:

If I need to change the name of a column, how do I do that? More specifically, how do I match the data to a different column name?

And, is there a way for me to dynamically create table headers via .DataTable() invocation? OR, should I restructure my JSON obj in some more preferred fashion?

I would love to see a solid example. Thank you for your patience and understanding.

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 20,299Questions: 26Answers: 4,769
    Answer ✓

    Here is an example of one way to dynamically define the column names. columns.data needs to match what you have in your JSON object. You can use columns.title to set the column title. Datatables will add the headers if they don't exist.
    http://live.datatables.net/fafuyeyu/55/edit

    One Datatables has been initialized you can't change the column structure unless you destroy() the Datatable first.

    Kevin

  • rldean1rldean1 Posts: 141Questions: 66Answers: 1

    @kthorngren -- yes -- that is helpful... I didn't know you could layer options like "title". I kinda just tried it, and this worked... but I haven't seen anything in the documentation yet that explicitly shows you can do something like this:

    $("#tblSomeFingTable").DataTable({
    "data": obj,
    "columns": [
    {
    "data": "Effective Date",
    "title": "Alternative Title 1"
    },
    {
    "data": "Description",
    "title": "Different Title 2"
    },
    {
    "data": "Locked",
    "title": "FOOBAR Title 3"
    },
    ],
    });

This discussion has been closed.