How to iterate through an array using Google Apps Scripts

I've been working on creating a loop for an array, but I keep encountering an error indicating that the string is invalid.

Suppose the keyword is "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 insights or suggestions?

Answer №1

Your error reference is originating from the following line:

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

In your code snippet above, this is the only instance where 'keyword' is used. Are you certain it is returning the correct information? Also, have you considered how your loop functions?

If your

var object = Utilities.jsonParse(jsondata.getContentText());
produces this output:

  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 if we use your loop as follows:

  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;
  }

Have you noticed that 'i' is never utilized in your loop? Additionally, you are repeatedly replacing values in results with the same data after each iteration. Is this truly your intended behavior?

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());

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using the `ko:if` binding in conjunction with a knockout binding provider preprocessor

I have been experimenting with using Knockout's bindingProvider API to bind custom elements, as a way to improve the readability of templates. In general, my processor is working well for most bindings. However, I am facing an issue with the if bindi ...

Send an unchangeable list to a component that needs an Array

Just diving into the world of React and learning that using .toJS() is not recommended due to its impact on performance. The dilemma I'm facing is that a third-party component I'm using requires an array as props, while my state is stored as an ...

Build an array containing the words from the user's input string in reverse order

I'm currently working on a project where users input a string of words (e.g., I love you), and the program should output an array with the words spelled backwards (e.g., I evol ouy). Unfortunately, my code isn't compiling properly even after mult ...

What could be causing this jQuery selector to not select any elements?

Here's a simple question with some code that needs troubleshooting: $insides = $('<thead><tr><th><!--Blank space --></th></tr></thead><tbody><tr class="green-row"><td>Opportunities to D ...

Encountering a DOM exception with React 16.6 due to lazy loading/Susp

I am currently working on implementing dynamic import in my React application. Most of the React examples I have seen involve rendering the application to a specific tag and replacing its content, like this: ReactDOM.render(<App />, document.getEle ...

Use jQuery to add an anchor tag before an image and then close the anchor tag

Here is the code snippet I am working with: <div id="slider"> <img src="images/p1.jpg" /> <img src="images/p2.jpg" /> <img src="images/p3.jpg" /> </div> I am looking to dynamically add <a> tags before ...

Convert the contents of the uploaded file to a JSON format

I've recently started using angularjs for file uploads and came across this helpful model on github: https://github.com/danialfarid/angular-file-upload The file upload process is working smoothly for me. However, I'm facing a challenge after upl ...

Steps for incrementing a number in an integer field with Node.js and MongoDB

I have a dataset that looks like this: { "_id": "6137392141bbb7723", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95f7e7fafafef0d5f6f4f2f9f0bbf6faf8">[email protected]</a>", ...

Using ng serve to upload multipart files in Angular 2

I am currently working on the front end of a file uploading service and have encountered a strange issue. When I restart the server using ng serve, it throws an error related to generated components within the app component. The error message can be seen h ...

When attempting to process JSON using the fetch method, the value for a valid JSON key

Currently, I am facing a challenge wherein I need to fetch data from my REST server to populate the frontend of my UI. This requires me to make requests not only to my own server but also to other servers. One specific request involves retrieving a list of ...

After changing the page, the Facebook JS SDK fails to function properly when using JQueryMobile

I'm facing an issue with my webapp that utilizes jQuery Mobile for full ajax navigation. I have initialized the Facebook SDK at the pageinit event in jQueryMobile (called on each page). jQuery(document).on('pageinit', function (event) { ...

Could this be a memory overflow issue? Utilizing Node.js handlebars partials

heap snapshots I execute the garbage collector before taking each snapshot. During testing with ab, it appears that the memory usage is increasing by 5mb for every 100 requests and does not decrease even after running the GC. It seems like there might be ...

Ensuring the slide toggle's status with Cypress validation

As a beginner in Cypress, I am looking to ensure that I can accurately determine the status of the slide toggle button - whether it is ON or OFF. The code below helps to check for this condition but I am unsure about how to implement it within an If-Else s ...

Guide to creating an asynchronous function

Starting my first react website and needing assistance with writing an asynchronous JavaScript function. I am currently working on uploading user input files to firebase storage and then making a post request to the API in order to store the data in the da ...

Custom Script for Single Tumblr Entry

While I know it's possible to edit the HTML/AngularJS for the overall posts on a Tumblr blog homepage, I'm wondering if there is a way to insert a custom <script>...</script> into individual posts. I have some specific JavaScript task ...

NextJS - Accessing local files with readdir and readFile functions leads to error: Module not found when trying to resolve 'fs' module

I have been working with NextJS and have successfully used the getStaticProps functionality in previous projects to populate data. However, I recently set up a new NextJS project and it seems that this functionality is no longer working. When starting th ...

Ways to insert a line break using ajax

document.getElementById("msg").innerHTML += "<strike>b:</strike> "+ msgs[i].childNodes[1].firstChild.nodeValue; After retrieving the messages, I noticed that they are all displayed close to each other. Is there a way to display each message on ...

JavaScript event triggered upon full completion of page rendering

Similar Question: How can I execute a JavaScript function after the page has fully rendered? I am aware that the onload() event can be utilized to perform actions once the page is completely loaded. Is there an equivalent event that signifies when the ...

Comparing JSON files in JavaScript to identify and extract only the new objects

I need a way to identify and output the newly added objects from two JSON files based on their "Id" values. It's important for me to disregard changes in object positions within the files and also ignore specific key-value changes, like Greg's ag ...

Errors are encountered when attempting to use `usePathname()` and `useRouter()` functions. `usePathname()` returns null while `useRouter()` causes errors stating "NextRouter not mounted" and "invariant

I'm encountering an issue with implementing active navlinks in NextJS version 13.4.4. I need to access the current URL for this solution, but every attempt ends up failing. My folder structure is organized as follows: .next components Header header ...