Issue arises when the function in a for loop disrupts the loop from functioning correctly

This particular script is designed to scan through a sheet for currency values and create key/value pairs for a JSON based on the column and row headers. It basically detects a currency value, then traces back row and column numbers until it reaches a non-currency, non-blank value which is used along with the currency to form pairs. There are three functions involved: one to enable the second by identifying if a value is currency, the second function builds the object, and the third one iterates through the sheets and constructs the object for each sheet that meets specific criteria.

Each sheet is named following a pattern like "name_name_type_location", and the specified criteria is anything with the type "AF".

The problem encountered is when calling tariffObject(sheets[i]) within publishedSheets(), it appears to disrupt the for loop, resulting in only receiving the first sheet object even though there are more than four sheets meeting the criteria. Removing the tariffObject(sheets[i]) call resolves the issue. There seems to be something causing this loop interruption.

How can this be resolved?

function isCurr(x){
  var regex = /^[$]\d+(?:\.\d{0,2})$/;
  if (regex.test(x)){
    return true;
  }
  else{
    return false;
  }
}

function tariffObject(sheet){
  // Function code...
}

function publishedSheets(){
  // Function code...
}

https://i.sstatic.net/tXrY7.jpg

Answer №1

Give this a try:

function generateJsonFromSheet() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet1');
  const [headers, ...dataRows] = sh.getDataRange().getValues();
  let jsonObj = { rows: [] };
  dataRows.forEach((row, i) => {
    row.forEach((cell, j) => {
      if (j == 0) {
        jsonObj[cell] = {};
        jsonObj.rows.push(cell);
      } else {
        jsonObj[dataRows[i][0]][headers[j]] = cell;
      }
    });
  });
  Logger.log(JSON.stringify(jsonObj));
  headers.shift();
  let output = '';
  jsonObj.rows.forEach((r, i) => {
    output += r + "={";
    headers.forEach((h, j) => {
      if (j > 0) output += ',';
      output += h + "=" + jsonObj[r][h];
    });
    output += '}\n';
  });
  Logger.log(output);

}

Data in Sheet1:

H1 H2 H3 H4 H5 H6 H7 H8 H9 H10
R1 1 11 21 31 41 51 61 71 81 91
R2 2 12 22 32 42 52 62 72 82 92

Output:

R1={H1=1,H2=11,H3=21,H4=31,H5=41,H6=51,H7=61,H8=71,H9=81,H10=91}
R2={H1=2,H2=12,H3=22,H4=32,H5=42,H6=52,H7=62,H8=72,H9=82,H10=92}
<!-- Additional outputs would follow for each row -->

The provided output is generated from the object shown below:

{"rows":["R1","R2",...], <Details of the individual rows> }

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

Is there a way to prevent the conversion of "u003c" to "<" when converting a JSON string to an object?

{"userName":"1_jan_\u003cscript>alert(1)\u003c/script> I have utilized ObjectMapper mapper = new ObjectMapper(); User user = mapper.readValue(input, User.class); as well as Gson g = new GsonBuilder().create(); ...

Exploring a List with APL Integration through an HTTP-Endpoint for Alexa

I am in the process of developing an Alexa Skill with my custom .NET-Backend. The goal is to generate an AlexaTextList containing dynamic content from my service. Here is a snippet of the request sent by Alexa: { "version": "1.0", " ...

Issue: A request is not pending for flushing during the testing of an AngularJs service

As a beginner in AngularJs, I am currently working on my first unit test. In order to test the service I created, I wrote a test that simply returns a single Json object. However, whenever I run the test, I encounter the error mentioned in the title. I am ...

I am looking to obtain assistance through denomongo for guidance

The deno-mongo guide page on GitHub is no longer functional. You can find the page here: 'https://github.com/manyuanrong/deno_mongo' I am struggling to understand how to use the plugin and get it up and running. Following the example in the "Re ...

What could be causing my code to retrieve duplicate items every time the page is loaded?

Currently, I'm diving into the world of React and attempting to fetch product data for a list. The goal is to initially fetch 2 items and then load 2 more items when a button is clicked. However, the issue I'm facing is that it's fetching t ...

I can't find my unit test in the Test Explorer

I'm currently working on configuring a unit test in Typescript using tsUnit. To ensure that everything is set up correctly, I've created a simple test. However, whenever I try to run all tests in Test Explorer, no results are displayed! It appear ...

The limit of update depth when using useState with an array generated from a map operation

I'm working on a component where I'm creating a list from an array using map. Each li element in the list has a ref attached to it to capture the getBoundingClientRect().x and getBoundingClientRect().y coordinates, which are then stored in a refs ...

Mocha test failing to trigger function execution

I've been developing an Express.js application that includes a feature for creating appointments with a post request. This feature involves retrieving and saving data from a third-party API, followed by sending updated API data in the subsequent reque ...

Twitter API causing issues with setTimeout function in Node.js

Attempting to read from a file and tweet the contents in 140 character chunks, one after the other has proven to be quite challenging. Despite verifying that other parts of the code are functioning correctly, using a simple for-loop resulted in tweets bein ...

Inheritance of Mongoose methods across all Schemas using the Schema method

Currently, I am working on nodejs with Mongoose and have data in various collections with _id as a string manually written by the user. I am looking to refactor this process and automate the generation of _id. My aim is to create a separate JavaScript fil ...

Refreshing ng-repeat dynamically with $http without reloading the page

Just a quick heads-up, I'm new to AngularJS In my AngularJS application, I am using the $http service to fetch data. Each row has an update button that needs to trigger a server-side method (the API is already returning data) to sync with a third-par ...

Exploring JSON data using Python - Tallying the number of cars and people

I am relatively new to Python and seeking guidance on extracting data from the JSON file provided below. I am in need of a Python script that can perform the following tasks: If the label is "Car" with a confidence level greater than 90, count the number ...

The Angular component router-outlet is not recognized as a known element

I have encountered an error message: 'router-outlet' is not a known element: 1. If 'router-outlet' is an Angular component, then verify that it is part of this module. 2. If 'router-outlet' is a Web Component then add ...

What is the best way to insert a hyperlink into the header of a column in a React table that is built using Material

// Here is the header const dataCells = [ {id:"Customer_ID",label:"CustomerId"}, {id:"Type", label: "Type"}, {id:"First_Name", label: "First Name"}, {id:"Last_Name", labe ...

Utilize dojo to manually trigger a window resize event

Is there a way to manually trigger the window resize event (the one that occurs when you resize your browser window) using Dojo? I need this functionality to dynamically resize my C3 Charts. I came across the on module in Dojo, which allows for listening ...

Potential risk of memory leakage when utilizing the CanvasRenderer

I've encountered a memory leak problem within my application. After some investigation, I've been able to simplify the issue into a test case found here: http://jsfiddle.net/729sv/ It seems that adding and removing geometry from a scene is causi ...

After the update, Material UI is causing a TypeError by throwing an error stating that it cannot read the property 'muiName' of an

After updating from "material-ui": "^1.0.0-beta.38" to "@material-ui/core": "^1.3.0", I made changes to imports, ran npm install, removed node_modules and even deleted package-lock.json. However, I continue to encounter the cryptic error message TypeError: ...

Is there a way to eliminate duplicates from an array in JavaScript by utilizing a set and placing each element in an li tag? Here is the code

const numbers = [" 4", "9", "16"," 4", "9", "16"," 4", "9", "16"] <ul> {(<li> {[...new Set(numbers)]} </li>)} </ul> const numbers = [" 4", "9", "16"," 4", "9", "16"," ...

There was an issue parsing the JSON Array from the response string received from the EC2 instance

In my development journey, I have created a Java RESTful web service hosted on an EC2 instance with Tomcat7 as the server. The challenge I am facing is with retrieving a JSON array from the response object of the web service. Here's a snippet of my re ...

Decoding GeoJSON: Extracting a feature from an array

I am currently working on a map project where I am drawing polygons with properties pulled from a JSON file. Each polygon is colored based on feature values in the JSON file. Here's an example of a feature in the JSON file: { "type": "Feature", " ...