devang_281999
devang_281999

Reputation: 65

how to combine multiple json data into single columns in jquery datatables?

I am getting this JSON response from to back-end.

{
  "data": [
    {
      "id": 6,
      "firstname": "fname",
      "middlename": "mname",
      "lastname": "lname",
    },
    ...
  ]
}

Creating table from the JSON response using jquery datatable using ajax request.

$number = 1;
$("#people-table").DataTable({
    ajax: {
        url: window.location.href + '/fetchdata',
        method: "GET",
        dataType: "json",
        dataSrc: "data"
    },
    columns: [
        {
            render: function () {
                return $number++;
            }
        },
        { data: 'firstname' },
        { data: 'middlename' },
        { data: 'lastname' },
    ]
});
<table>
  <thead>
     <tr>
        <th>No.</th>
        <th>Profile</th>
        <th>Firstname</th>
        <th>Middlename</th>
        <th>Lastname</th>
    </tr>
  </thead>
  <tbody>
      {{-- data --}}
  </tbody>
</table>

I am getting proper output for this code in the html table, but now I want to combine all three field firstname, middlename, and lastname into one field called fullname using jquery datatable

Upvotes: 0

Views: 701

Answers (1)

JSTR
JSTR

Reputation: 151

You can do something like this instead of DataTables. This is a pure javascript example.

HTML

 <thead>
  <tr>
     <th>No.</th>
     <th>Profile</th>
     <th>Full Name</th>
 </tr>
</thead>
<tbody id="myDataTable"></tbody>

Javascript

       <script>

       function MyFunction(){
        $.ajax({
         url: 'your-url' ,
         type: 'get',
         datetype:"json",
         success: function(res){
            var myData = res.data //collection from backend
            let str = "";
            myData.forEach((data, key) => {
                str += `
                    <tr>
                        <td> ${data.no} </td>
                        <td> ${data.profile} </td>
                        <td> 
                           ${data.firstname} 
                           ${data.middlename}
                           ${data.lastname} 
                        </td>
            
                    </tr>
                 `
            })
            $("#myDataTable").html(str);
         }
        })
       }
      
    </script>

Make sure to call your function whenever you need it to display.

Upvotes: 1

Related Questions