Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap tables - how to access inner elements in the data source object

Let's say my data source object looks something like this:

[{
   "id": 123,
   "name": "blabla1",
   "kids": {
      "id": "kid1",
      "name": "kk1"
   }
},{
   "id": 456,
   "name": "blabla2",
   "kids": {
      "id": "kid2",
      "name": "kk2"
   }
}]

This is a list (array) containing 2 objects, with the "kids" key in each, holding an inner object with keys and so on.

When working with Bootstrap Tables, each column is connected to a key in the source object, for example:

<th data-field="id">ID</th>

The question here is how can I define a column to be connected to an inner key in the source object??

I've tried the following thing (suited for the example data above):

<th data-field="kids.id">Inner ID</th>

And it doesn't work. :(

P.S:

I know that I can format each column's data by implementing the designated "data-formatter" attribute, but I prefer to find a more direct and faster way to accomplish what I need in this case.

like image 403
TheCuBeMan Avatar asked Jan 10 '23 17:01

TheCuBeMan


1 Answers

This Bootstrap plugin bootstrap-table does not offer the mechanism to do this at the moment. You should raise an issue on their github site to request this.

Instead, you will have to flatten the JSON every time in the plugin's response handler before loading it into the table. Using the code to flatten JSON from the accepted answer to this question: Fastest way to flatten / un-flatten nested JSON objects, you can create a responseHandler as follows:

<script>
    function responseHandler(res) {
        var flatArray = [];
        $.each(res, function(i, element) { 
            flatArray.push(JSON.flatten(element));
        });
        return flatArray;
    }
</script>

And then add the response handler to your table using the attribute data-response-handler="responseHandler":

<table data-url="data.json" data-toggle="table" data-height="299"  data-response-handler="responseHandler">
    <thead>
    <tr>
        <th data-field="id">ID</th>
        <th data-field="name">Name</th>
        <th data-field="kids.id">Kids Id</th>
        <th data-field="kids.name">Kids Name</th>
    </tr>
    </thead>
</table>

Plunker example here

like image 193
mccannf Avatar answered Jun 09 '23 12:06

mccannf