Insert an array to existing datatable javascript

I have a dataTable where I insert data manually with a form

this is my dataTable
enter image description here

I trying to create an import CSV function with an import button

I would like to use dataTable.rows.add (for example) with an array that I have since I get the CSV,

this is my array result that I like to add to my table

[{"URL":"htpp://www.google.com2","Business Type":"Restaurant2"},{"URL":"htpp://www.google.com3","Business Type":"Hotel"}]

how can I add this data to my table? actually, my dataTable is already initialized with this code

let dataTable = $('#task-place-table').DataTable({
        processing: true,
        autoWidth: false,
        responsive: true,
        dom: '<t>ip',
        order: [0, 'asc'],
        language: {
           "url": '{{session('locale') == 'en' ? "//cdn.datatables.net/plug-ins/1.10.20/i18n/English.json" : "//cdn.datatables.net/plug-ins/1.10.20/i18n/Japanese.json"}}',
        "buttons": {
        "reload": '{{__('tableButtons.reload')}}'
                    }
                }
            });

and I add rows with "add place" buttons with row.add using this code

  dataTable.row.add([
     itemCounter,
     placeUrl,
     businessType[0].text,
     '<button id="btn-remove-' + itemCounter + '" class="btn btn-outline btn-primary btn-xs deleted" ' +
      'data-id="' + itemCounter + '" data-toggle="tooltip" title="Delete" type="button"><i class="fa fa-trash"></i></button>'
     ]).draw(false);

actually, placeUrl, itemCounter and businessType are obtained by form elements with document.getElementById.value

the respected result is this

Item = itemCounter (this is already calculated)
Place URL = first data in array
Business Type = second data in array

my HTML table only has this

<table id="task-place-table" class="table table-striped table-bordered table-hover">
       <thead>
         <tr>
           <th class="desktop mobile">{{__('task.columns.item')}}</th>
           <th class="desktop tablet mobile">{{__('task.columns.place_url')}}</th>
           <th class="desktop tablet">{{__('task.columns.business_type')}}</th>
           <th class="desktop">{{__('task.columns.actions')}}</th>
         </tr>
       </thead>
      <tbody></tbody>
 </table>

thanks for read this 🙂

14 thoughts on “Insert an array to existing datatable javascript”

Leave a Comment