title: Google sheet : Get values from the web and keep value matching each file in a folder
body: <p>I am trying to do something and I am almost there but I have been scratching my head on a 'length' issue for quite some time now.
  What I want to do :</p>
  <ul>
  <li>Get data from an URL (web csv file)</li>
  <li>Loop through all spreadsheets in a folder</li>
  <li>For each spreadsheet only keep the data from the web csv file that contains the spreadsheet's name.</li>
  </ul>
  <p>My code works on a single page but not when I try to apply it to all spreadsheets in the folder.
  I have this error : &quot;TypeError: Cannot read property 'length' of undefined
  myfunction  @ Getproductfiles.gs:35&quot;</p>
  <p>Here is the full code :</p>
  <pre><code>function myfunction()
  { 
   var root = DriveApp.getFoldersByName(&quot;Produits&quot;);                                        
    while (root.hasNext())
    { 
     var folder = root.next();    //If the folder is available, get files in the folder
     var files = folder.getFiles();                                                                       
     while(files.hasNext())       //For each file,                                                                    
     { 
      var spreadsheet = SpreadsheetApp.open(files.next()); 
  
      //import data from URL
       var csvUrl = &quot;https://incensy.tempurl.host/test-ct-flux.csv&quot;;
    var csvContent = UrlFetchApp.fetch(csvUrl).getContentText();
    var csvData = Utilities.parseCsv(csvContent);
   
    var sheets = spreadsheet.getSheets()
    var sheetIndex=0
    var sheet = sheets[sheetIndex]
     sheet.getRange(2, 1, csvData.length, csvData[0].length).setValues(csvData);
  
  // Always show 3 decimal points
  var cell = sheet.getRange(&quot;D2:D&quot;);
  cell.setNumberFormat(&quot;00&quot;);
  
  //Only keep data that contains the file name
    var name = spreadsheet.getName();
    let range = sheet.getDataRange(),
        maxRows = sheet.getMaxRows(),
        srchCol_1 = 2,
        srchPatt_1 = new RegExp(name)
        newRangeVals = range.getValues().filter(r =&gt; r[0] &amp;&amp; srchPatt_1.exec(r[srchCol_1])),   
        numRows = newRangeVals.length;  
    range.clearContent();
    sheet.getRange(2,1, numRows, newRangeVals[0].length).setValues(newRangeVals);
    sheet.deleteRows(numRows + 1, maxRows - numRows);
  
  //Clean headers
  var cell = sheet.getRange(1,1);
  cell.setValue(&quot;Column1&quot;);
  var cell = sheet.getRange(1,2);
  cell.setValue(&quot;Column2&quot;);
  var cell = sheet.getRange(1,3);
  cell.setValue(&quot;Column3&quot;);
  var cell = sheet.getRange(1,4);
  cell.setValue(&quot;Column4&quot;);
  var cell = sheet.getRange(1,5);
  cell.setValue(&quot;Column5&quot;);
  var cell = sheet.getRange(1,6);
  cell.setValue(&quot;Column6&quot;);
  
     }
    }
   }
  </code></pre>