Looping through dates in a POST request using JavaScript/GAS - What's the best approach?

My task involves posting timesheet entries for the upcoming month into a system using an API. In order to do this, I require the following:

  1. User ID
  2. Assignable ID
  3. Dates (in the format YYYY-MMM-DD)
  4. Hours

Initially, I obtained the user_id and assignable_id and stored them in an array. Now, I am attempting to utilize them to make a POST request to the system.

My current challenge lies in including dates in an array and iterating through each day in the array during the POST requests. Any suggestions on how I can accomplish this within the POST loop?

Below is the code for the POST request:

function demo_Code()
{
var user_dt = user_assignments()

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

     var data = {

      'hours': 0,
//      'date': lastRow[0][2],   // This is where I need to change and have next one month datesin an array instead of reading through the sheet
      'user_id': user_dt[i].user_id,
      'assignable_id': user_dt[i].assignable_id,
    };
    var payload = JSON.stringify(data);
    var options = {
      'method': 'POST',
      'Content-Type': 'application/json',
      'payload': data,
    };

    var url = 'https://api.10000ft.com/api/v1/users/' + data.user_id + '/time_entries?auth=' + token
    var response = UrlFetchApp.fetch(url, options);
     }

}

Answer №1

Based on the information provided in your question and subsequent comments, it appears that you are looking to create an array of dates encompassing all the days between two specific dates.

To accomplish this, the following straightforward code can be utilized, which includes explanatory comments. Essentially, the code loops through each day between the two dates by incrementing the day count after adding each day to the array. This functionality is achieved through the utilization of the getDate() and setDate() functions.

If you intend to utilize this array in a POST loop, you can easily access individual dates by their respective index, such as dateArray[2]. Additionally, this index can also serve as your iteration variable, denoted by i (dateArray[i]).

 // Array of dates
 var dateArray = [];
 // Start date
 var date1= new Date(2021,1,1);
 // End date within the date range
 var date2 = new Date(2021,1,31);

// Set the current date to the start date 
 var date = new Date(date1); 

// Loop through all dates from the start
// to the end date
 while(date<=date2){
 // Add the current date
   dateArray.push(date);
 // Increment the current date by a day
   date.setDate(date.getDate()+1);
 }
// Display your date array
 Logger.log(dateArray);

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

Scrolling horizontally in vue-chartjs-chartwidget

I have a question regarding vue-chartjs. I am looking to achieve a similar result to the one demonstrated in this jsfiddle example: http://jsfiddle.net/mbhavfwm/ Below is the code for my Vue.js component (Chart data is passed through params). &l ...

Utilizing Jquery Ajax to send a post request containing input values through Tampermonkey

I encountered an issue with my code - even though the logs in console show that it is working, I am unable to send the values to my server using AJAX post. jQ(document).on("keyup", "form input", function () { var value = jQ(this).val(); ...

Receiving an error of "undefined" when trying to capture the selected

One issue I am facing is capturing the selected user option and sending that value in a post request. Let's put aside the post part since it's not directly related to the main question at hand. Currently, the value is showing up as undefined. ...

The function getattribute() on the edge is malfunctioning and returning a null value

Has anyone encountered issues with the getAttribute() function while creating an extension for Edge? I am currently facing a problem where it is not returning the attributes of the element that I am searching for. This is what my code looks like on Edge a ...

Trying to incorporate a PHP echo statement into the innerHTML of a button is ineffective

I have a piece of jQuery code that is not functioning as expected: $("#erase").click(function(){ $("#erase").attr("disabled", "disabled"); // Prevent double-clicking $(this).html("Erasing..."); $.post("erase.php", {target: $("#targ ...

Tips for distinguishing individual rows within a table that includes rowspans?

My Vue application calculates a table with rowspans by using an algorithm based on a configuration file. This allows the application to render columns (and maintain their order) dynamically, depending on the calculated result. For example, see the code sn ...

Include criteria in my ajax call (conditional statements)

Is there a way to add conditions to my ajax request? Whenever I include the code below, it only seems to work for one item at a time. $.ajax({ type: 'GET', url: urlPost, success: function (data) { $.each(data, function (key, value) { ...

Bidirectional data binding in Vue.js enables seamless communication between parent and child components, allowing for dynamic

Trying to implement v-for and v-model for two-way data binding in input forms. Looking to generate child components dynamically, but the parent's data object is not updating as expected. Here's how my template is structured: <div class="cont ...

The waypoints.js snippet seems to be malfunctioning in this specific context

After experimenting with waypoints.js (jQuery.waypoints) for some time, I've been attempting to utilize this library to incorporate animations on children elements within a specific container. Here is the approach I have taken: var waypoints = $( ...

The Vue store array declaration triggers a TS error stating that it is not assignable to a parameter of type never

I'm puzzled as to why this error keeps showing up: Argument of type '{ id: string; }' is not assignable to parameter of type 'never'. ... appearing at const index = state.sections.findIndex((section) => section.id === id); T ...

Transform them into async/await in JavaScript

Exploring the promise-retry library, I discovered the following syntax: promiseRetry(function (retry, number) { return doSomething() .catch(retry); }) .then(function (value) { // .. }, function (err) { // .. }); Since I am utilizing a ...

Unable to set selected property in React Material-UI menu item

One issue I'm facing is setting the selected prop using react mui menu item. In a multiple select menu list, there's a field called allValues that, when clicked, should toggle the selection of all menu items. The code for this functionality looks ...

Issue: .catch(error) function in Node / Express not returning as expectedDescription: After

I'm currently developing a REST API and focusing on effectively managing all error scenarios. Upon successful completion of the API call, I make sure to return the success object to the calling function and then send the response to the client. Howev ...

Object with a specific name sitting within an array nested within another object

I have a node.js model that includes an array called keys containing multiple objects. I am looking to display these named objects in the view. Below is the model: var mongoose = require('mongoose'); var website = require('./website' ...

Sending a massive video file to a node.js server and saving it in AWS S3 with ReactJS

I am currently in the process of creating an OTT platform, but I have encountered a problem while attempting to upload large files to the server. I initially attempted to store the file in a temporary folder using multer and then utilize aws-sdk s3.upload. ...

What sets apart .create from .save in mongoose?

A while ago, I completed a bootcamp course on Express and Mongoose on Udemy. In the course, we learned how to add new fields to data by writing code like this: var playground = require("../models/playground.js"); route.post("/", middleware.isLoggedIn,fun ...

Error message: "Link binding error in knockout collection"

In this example, you'll find my Knockout ViewModel. $(document).ready( function () { var Incident = function (CaseNumber, DateOfIncident, Description) { this.CaseNumber = CaseNumber; this.DateOfIncident = DateOfIn ...

Calculate the total and average of related values with the associative array having identical keys

I'd like to build upon the discussion located at Associative array, sum values of the same key. https://i.sstatic.net/YO7BO.jpg The original poster inquires: Instead of having the key "Conference" repeating 3 times. I want to have it just once an ...

Showing the Datepicker from jQuery right in the middle of the screen

Here's the generated code as default: <div id="ui-datepicker-div" class="ui-datepicker ui-widget ui-widget-content ui-helper- clearfix ui-corner-all ui-datepicker-multi ui-datepicker-multi-2" style="width: 34em; position: absolute; left: ...

Creating indexes for a two-dimensional NumPy array

In my pursuit to create a 2D numpy array with elements derived from their positions, I developed the following code snippet: import numpy as np def calculate_element(i, j, other_parameters): # do something return value_at_i_j def main(): arr ...