badbyte
badbyte

Reputation: 93

Dynamically adding / removing columns

I use datatables 1.10 for a while now, and I have come to a point in my development where I have a table in my db that stores a json object. Furthermore that table also contains an attribute called groupName. As the name suggests, the entries of that table are "grouped" by that attribute, and in that group, the json object has the same attributes.

Here an example of how my database table looks like:

+---------------------------------------------------------------------------+
|id|groupname                   |json                                       |
+---------------------------------------------------------------------------+
|01|group1                      |{"key1":"value1","key2":"value2"}          |
|02|group1                      |{"key1":"foo","key2":"bar"}                |
|03|group2                      |{"kex1":"foo1","keyab":"bar2","key1":"foo"}|                                               
+---------------------------------------------------------------------------+

My page that contains the datatabase, and also has a dropdown menu populated with the group names which filters the the datatable for the particular group. The jsonObject of that filtered group is being displayed as a raw json string.

What I'm trying to do now is to parse my jsonObject, get the keys and populate them in the datatable as columns. The values of the jsonObject are displayed in the columns accordingly.

Where or how do I reinitialize the datatable, providing it with the proper column names?

Upvotes: 1

Views: 84

Answers (1)

Chirag Arora
Chirag Arora

Reputation: 357

Can you please share some example of your JSON object. Thanks! Any ways what you can do is to to take the keys of the json object and put them into array then using loop you can make a string of columns. Then you can provide an id to of the table and append the string into the table.

let keys = Object.keys(YOUR_JSON_OBJECT);
let text = "";
for(let i =0;i<keys.length;i++){
text+= ["<tr>","<td>",YOUR_JSON_OBJECT.its_key,"</td>","</tr>"].join("");
}
$('table thead').html(text);

See if this works!

Upvotes: 1

Related Questions