What is the best way to access an array from a separate function in JavaScript or Google Apps Script?

Currently, I am developing a function that aims to retrieve total time entries from an external API. The primary task of this function is to fetch user data containing the id stored in an array. Subsequently, the retrieved ID must be utilized by a secondary function to accumulate and store the total hours for a specific data range into another array. You can find the Systems API at https://github.com/10Kft/10kft-api

This is my initial function responsible for retrieving user data:

function get_users() {
    // This function iterates through 10000ft paginations to gather user data into an array
    var userarray = [];        
    var lastpage  = false;
    var page      = 1;

    do{        
        // Fetches data from 10kft
        var users = read10k_users(page);            
        // Writes data from current page to the array

        for (i in users.data) {
            var rec     = {};
            // Pushing mandatory data
            rec.id      = users.data[i].id;
            rec.display_name = users.data[i].display_name;
            rec.email   = users.data[i].email;                
            userarray.push(rec);

        }

        Logger.log(userarray)
        // Checks if this is the last page (indicated by paging next page link being null)
        if (users.paging.next != null) {
            lastpage = false;
            var page = page + 1;
        } else {
            lastpage = true;
        }

    }while (lastpage == false);

    return (userarray);

}

The second function is supposed to utilize the saved ids in the array to calculate the total hours for specific users, but I'm facing some challenges in implementing it.

function get_timedata(id) {
    // This function loops through 10000ft paginations to scrape time entries into an array
    var timearray = [];        
    var lastpage  = false;
    var page      = 1;

    do{

        // Retrieves time data from 10kft 
        var timedata = read10k_timedata(from_dt,to_dt,); 

        // Writes data from the current page to the array

        for (i in timedata.data) {
            var rec       = {};
            // Collects time data from time entries endpoint
            rec.id        = timedata.data[i].id;
            rec.user      = timedata.data[i].user_id;
            rec.hours_inc = timedata.data[i].hours;                 

            // Adds incurred hours to the array      
            if (rec.hours_inc >= 0 ) {
                timearray.push(rec);                
            }
            //Logger.log(timearray)
        }

        // Checks if this is the last page (indicated by paging next page link being null)
        if (timedata.paging.next != null) {
            lastpage = false;
            var page = page + 1;
        } else {
            lastpage = true;
        }

    }while (lastpage == false);        
    return (timearray);

}

I would greatly appreciate any assistance or guidance on how to proceed with solving this issue. Thank you in advance!

Answer №1

If my understanding is correct, you are looking to:

  • Save an array of JavaScript objects returned by a specific function.
  • Utilize this stored array in a function that will be used at a later time.

To achieve this, you can employ the PropertiesService to store your data. This tool enables scripts to store basic data in key-value pairs.

Keep in mind that only strings can be stored and you wish to store an array of JS objects. Therefore, before storing this data as a script property, you must first utilize JSON.stringify() to convert a JavaScript object or value into a JSON string.

Later on, when you need to access the data, simply use JSON.parse() to convert the string back into an array of objects.

Workflow:

To summarize, in the get_users function, convert the userarray to a JSON string and store it as a script property using setProperty(key, value), like so:

var value = JSON.stringify(userarray);
var scriptProperties = PropertiesService.getScriptProperties();
scriptProperties.setProperty("your-key", value);

Then, whenever you need to retrieve that data (in the get_timedata function or any other function calling this one), retrieve the property with getProperty(key) and convert it back into an array of objects, as shown below:

var scriptProperties = PropertiesService.getScriptProperties();
var value = scriptProperties.getProperty("your-key");
var obj = JSON.parse(value);

You can now access the different ids within the array just like you would with the original array (e.g. obj[0]["id"]).

Reference:

I hope this guidance proves helpful.

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

What is the best way to monitor a document variable that is set after a component has been

Is there a way to access the variable document.googleAnalytics, added by Google Tag Manager, for A/B testing on a Vue.js page? I attempted to initialize the variable in both the mounted and created methods of the component, but it returns as undefined: ex ...

How to parse an array in JSON using Swift 3 and iterate through it

Figuring out how to parse JSON data in Swift 3 has been more challenging than I anticipated, especially coming from a Javascript background. Received response from API: [ { "ID": 1881, "image": "myimageURL", }, { "ID": 6333, "image": "myi ...

An issue with npm arises on Windows 10 insider preview build 14366

It appears that npm and nodejs are experiencing issues on the latest Windows version build 1433 When I ran the following command: npm -v events.js:141 throw er; // Unhandled 'error' event ^ Error: This socket is closed. ...

Is it possible to have a shared script in ASP.NET that can be used for both client-side and server-side

Currently, I am developing a web application that involves a calculation method which takes a string as input and returns the number of SMS messages. This function is self-contained and does not rely on any external resources to operate. I need this funct ...

Sharing variables between Angular 2 components: An in-depth guide

Looking for a way to change a variable in a group of child components, I have this component for an editable form control that toggles between view states import { Component, Input, ElementRef, ViewChild, Renderer, forwardRef, ...

Validating fields using JavaScript and HTML

I'm having an issue with the code below because it only allows me to log in with the user and password from the last position of the arrays. I want it to let me login with each user and their corresponding password, for example, user at position 1 wit ...

What is the purpose of having a constructor in Typescript when an interface is already used for a class?

Is it necessary to have a constructor in my class if the class already implements an interface? It seems like redundant code to me. interface PersonInterface { firstname: string; lastname: string; email: string; } class Person implements Pe ...

Activate Button upon Textbox/Combobox/RadDatePicker Modification through JavaScript

On my ASP.NET form, I have various input elements including textboxes, dropdowns, date pickers, and update buttons. My goal is to enable the update button whenever a user makes a change in any of these fields. To achieve this, I applied a specific CSS cla ...

Is it possible to retrieve all dependencies listed in a package-lock.json/yarn.lock file without actually installing them?

Seeking a way to organize dependencies from the NPM registry in a Nexus NPM proxy repository for any JavaScript project without having to run npm install or yarn install due to potential C/C++ compilation requirements for NodeJS C/C++ add-ons. One method ...

collecting JavaScript objects directed to console.log

I attempted capturing the JavaScript console log using the method mentioned here on Stack Overflow. However, I am facing difficulty in retrieving the object along with a text message. Below is the code snippet that I have been working with: var obj={resul ...

Is there a way to update a .json value using commands in Discord?

As a beginner in coding, I have successfully created a Discord bot using Node.js that has the ability to modify the entire config.json file, start and stop the bot, and create instances. However, I am currently facing a challenge where I need to update a s ...

Is the typeahead feature acting unusual - could this be a glitch?

My input field uses typeahead functionality like this: <input type="text" id="unit" name="unit" class="form-control form-input" ng-model="item.unit" autocomplete="off" typeahead-min-length="0" uib-typeahead="unit a ...

Using tokens to make consecutive API calls in JavaScript/Node.js

After generating the token, I need to make sequential calls to 5 different APIs. The first API used to generate the token is: POST https://idcs-xxxx.identity.c9dev2.oc9qadev.com/oauth2/v1/token Using the username and password, I will obtain the token from ...

Is there a way to selectively remove certain strings from an array?

I'm struggling to filter out strings in an array that don't meet a specific length requirement. The assignment suggests using map or map!. I've been experimenting with map!, delete_if, and keep_if, but haven't made progress. Can someone ...

Tips on concealing modal popup when the page refreshes successfully

I implemented a progress modal popup to show progress for page reloads. This script is set to the master page and injects the progress modal popup when the form submit event is fired: <script type="text/javascript"> function ...

The Stencil EventEmitter fails to send data to the Vue instance

Attempting to develop a custom component using Stencil with an input feature. The goal is to create a component with an input field that, upon value change, emits the input to the Vue instance and logs this event to the console (later updating the value in ...

When the button onClick event is not functioning as expected in NextJS with TypeScript

After creating a login page with a button to sign in and hit an API, I encountered an issue where clicking the button does not trigger any action. I have checked the console log and no errors or responses are showing up. Could there be a mistake in my code ...

Obtain a range of dates within a specified timeframe by utilizing JavaScript

Is there a way in JavaScript to retrieve a list of days between two dates in MySQL format without using any libraries? Here is an example of how it can be done: function generateDateList(from, to) { var getDate = function(date) { //MySQL Format ...

Remove a property from an object using Object.assign()

Is there a way to remove a key using Object.assign() rather than setting the value to undefined in this scenario? In my code, I am utilizing .filter() to iterate through certain items. When a match is found, I aim to modify the x-property value while also ...

Learn how to implement console-like Tail functionality in a web application using the MaterialUI TextField component as the console interface

Issue with Component: Scroll not Updating as new content is added to TextField: https://i.sstatic.net/lgOtn.png I am currently in the process of developing a live console feature within a React application and I wanted to utilize MaterialUI's TextFie ...