Home > Blockchain >  Adding headers to filters data in Google AppScript
Adding headers to filters data in Google AppScript

Time:10-10

I need to send filtered spreadsheet data to a html. Data filtered using following code.

    function getAllData() {

  var values = getByName('user3')
  Logger.log(values)
  return values
// DataTable.html calling this function with create table. But Data not showing in webApp deploy 
 }

function getByName(user, colName = 'userID') {
  const sheet = SpreadsheetApp.getActiveSheet();
  const data = sheet.getDataRange().getValues();
  const hA = data.shift();
  const idx = hA.reduce((a, h, i) => (a[h] = i, a), {});
  let o = data.map(r => {
    if (r[idx[colName]] == user) {
      return r;
    }
  }).filter(r => r );
  if (o && o.length > 0) {
    return o;
  }
}

My html datatable code is as below

 function createTable(dataArray) {
      $('#btn-close').click()
      $(document).ready(function(){
     
      $('#dataTable').DataTable({

    //data: dataArray,
      data: dataArray.slice(1),
     columns: [
      { title: "Productname" },
      { title: "Price1" },
      { title: "Price2" },
      { title: "Price3" }, 
      { title: "Price4" }, 
      { title: "userID" },
               
 { title: "Edit", "render": function (data,type){
              return "<button type='button' class='btn btn-outline-warning btn-xs editBtn' data-toggle='modal' data-target='#myModal' onclick='editData(this);'><i class='fa fa-edit'></i></button>";
            }
        },

 { title: "Delete", "render": function (data,type){
              return "<button type='button' class='btn btn-outline-danger btn-xs deleteBtn' onclick='deleteData(this);'><i class='fa fa-trash''></i></button>";
            }
        },
     ],
    //  "ordering": false,
       destroy:true, 
       responsive:true,     
       lengthMenu: [
          [10, 15, 25, 50, 100, -1 ],
          ['10', '15', '25', '50','100', 'All' ]
      ],
      
      order: [[2, "asc"], [2, "asc"], ],
      });
    });
  }

Spreadsheet link

Data screenshot picture

Above data filtering is doing absolutely correct. Issue is Headers are not available. Therefore DATATABLE.html not working.

I tried to use following code. but I tried replacing return r and return o in above function getByName

const headers=data.shift()
return { data:data,headers: headers} 

But I get code error.

log report original

Log error adding header

CodePudding user response:

One way to fix this is by inserting the headers after the filtering by using Array.prototype.unshift

function getByName(user, colName = 'userID') {
  const sheet = SpreadsheetApp.getActiveSheet();
  const data = sheet.getDataRange().getValues();
  const hA = data.shift();
  const idx = hA.reduce((a, h, i) => (a[h] = i, a), {});
  let o = data.map(r => {
    if (r[idx[colName]] == user) {
      return r;
    }
  }).filter(r => r );
  if (o && o.length > 0) {
    o.unshift(hA); // < ------------
    return o;
  }
}
  • Related