Loop an array in Google Apps Scripts

10,873

Your reference error is coming from this line:

var jsondata = UrlFetchApp.fetch("http://api.grepwords.com/lookup?apikey=carter&q="+keyword);

From your above code, this is the only moment where you use 'keyword'. You sure it returns the correct information? And if it does have you thought about your loop?

Suppose your var object = Utilities.jsonParse(jsondata.getContentText()); returns this:

  var object = [
      {cpc: 'test1', cmp: 'test2', lms: 'test3', m1: 'test4'},
      {cpc: 'test5', cmp: 'test6', lms: 'test7', m1: 'test8'},
      {cpc: 'test9', cmp: 'test10', lms: 'test11', m1: 'test12'}
  ];

And we use your loop:

  for (var i = 0; i < object.length; i++) {

  results[0] = object[0].cpc;
  results[1] = object[0].cmp;
  results[2] = object[0].lms;
  results[3] = object[0].m1;
  }

You do realize you never use 'i'? and you overwrite what you had in results with the same thing after each loop? Are you sure you wanted this?

function somefunc() {

  var object = [
      {cpc: 'test1', cmp: 'test2', lms: 'test3', m1: 'test4'},
      {cpc: 'test5', cmp: 'test6', lms: 'test7', m1: 'test8'},
      {cpc: 'test9', cmp: 'test10', lms: 'test11', m1: 'test12'}
  ];
  var results = Array("Error", "Error", "Error", "Error");

  if (object[0] != undefined)
  {
  results[0] = object[0].cpc;
  results[1] = object[0].cmp;
  results[2] = object[0].lms;
  results[3] = object[0].m1;
  }

  for (var i = 0; i < object.length; i++) {

  results[0] = object[0].cpc;
  results[1] = object[0].cmp;
  results[2] = object[0].lms;
  results[3] = object[0].m1;
  }

  return results;
}

console.log(somefunc());

Share:
10,873
ethanenglish
Author by

ethanenglish

Updated on June 04, 2022

Comments

  • ethanenglish
    ethanenglish almost 2 years

    I'm trying to write a loop for an array but getting an invalid string error.

    If keyword = "mesothelioma|seo"

    function json(keyword) {
      var jsondata = UrlFetchApp.fetch("http://api.grepwords.com/lookup?apikey=carterq="+keyword);
      var object = Utilities.jsonParse(jsondata.getContentText());
    
      var results = Array("Error", "Error", "Error", "Error");
    
      for (var i = 0; i < object.length; i++) {
    
      results[0] = object[0].cpc;
      results[1] = object[0].cmp;
      results[2] = object[0].lms;
      results[3] = object[0].m1;
      }
    
      return results;
    }
    

    Any thoughts?