2

I have a script in which the row data of a google sheet is stored into a JSON. I'd like to filter the data that is stored in the array.I don't want the empty cells to be inserted into the array. I want only the filled cells to be inserted into the array .Here is the script I'm using

  var dataArray = [];
  var rows = sheet.getRange(2,1,sheet.getLastRow()-1, sheet.getLastColumn()).getValues();

  for(var i = 0, l= rows.length; i<l ; i++){
    var dataRow = rows[i];
    var record = {};
    record['name'] = dataRow[0];
    record['age'] = dataRow[1];
    record['weight'] = dataRow[2];

    dataArray.push(record);   
  } 
skellertor
  • 602
  • 5
  • 21

1 Answers1

2

I think what you're really looking for is the .filter method to get rid of the empty cells, and then you can use a .map to transform them:

var rows = sheet.getRange(
  2,
  1,
  sheet.getLastRow() - 1,
  sheet.getLastColumn()
).getValues();

var filteredDataArray = rows.filter(function(row) {
  return row[0] !== ''; // Based on your comment that "empty" means it's an empty string
});

var transformedDataArray = filteredDataArray.map(function(row) {
  return { name: row[0], age: row[1], weight: row[2] };
});
Matthew Herbst
  • 21,357
  • 19
  • 68
  • 107