Tips for looping through nested JSON data in Google Sheets

In my attempt to iterate through the nested "line_items" element in a JSON response triggered by a post event, I aim to populate a Google Sheets spreadsheet using Google Apps Script. My objective is to write the elements within each "line_item" into new rows as shown in the image below:

https://i.sstatic.net/RDCit.png


        {
            "purchaseorder": {
                "date": "2019-11-27",
                "submitted_date": "",
                "delivery_address": {
                    "zip": "91240"
                },
                ...
                ...
            }
        }
    

The code provided here is the result of my efforts and although it doesn't perform as expected, I've managed to successfully write JSON data to a spreadsheet using a different approach before.


        // Function to handle POST request to the webapp
        function doPost(e) {    

            // Exit if no data is received
            if (e == undefined) {    
                console.log("no data");    
                return HtmlService.createHtmlOutput("need data");   
            }    

            // Get the active spreadsheet and specify the target sheet
            var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
            var sheet = spreadsheet.getSheetByName('Sheet3'); 

            // Parse the JSON data from the POST request
            var event = JSON.parse(e.postData.contents);  
            var data = event.purchaseorder;

            // Iterate through the data and populate the rows array
            var rows = [];
            var items;
            for (var i = 0; i < data.line_items.length; i++) {
                items = data.line_items[i];
                rows.push([items.name, items.quantity, items.rate]);
            }

            // Write the data to the specified sheet 
            dataRange = sheet.getRange(1, 1, rows.length, 3);
            dataRange.setValues(rows); 
        }
    

Any assistance in debugging and improving this code to achieve the desired outcome will be highly appreciated.

Answer №1

'data' is being used as an object in this scenario rather than an array.

let data = event.purchaseorder;

However, it seems like you are attempting to iterate over it.
The 'line_items' is actually the array you should be looping through. Therefore, the for loop should be adjusted as follows:

// updated loop
...
for (let i = 0; i < data.line_items.length; i++) {
    items = data[i];
    rows.push([data.date, data.line_items[i]]);
  }

I hope this clarification helps!

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

Executing Node.js child processes: streaming stdout to console as it happens and running the processes one after the other

Details node: v9.4.0 I am looking for a solution to execute external commands sequentially while monitoring the stdout in real-time. The code snippet below demonstrates my attempt to retrieve all test cases from ./test/ and then running them one after ...

How do I adjust brightness and contrast filters on a base64 URL?

When presented with an image in base64 format like this: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABDAAwfqNRk/rjcYX+PxrV/wtWqwJSTlboMgAAAABJRU5ErkJggg== What is the most efficient method to programmatically alter a filter (such as brightness or cont ...

JavaScript's async function has the capability to halt execution on its own accord

Presented here is a JavaScript async function designed to populate a sudoku board with numbers, essentially solving the puzzle. To enhance the user experience and showcase the recursion and backtracking algorithm in action, a sleeper function is utilized b ...

Can a custom function be executed using setTimeout in Node.js?

I am currently facing an issue with stopping the execution of my code for 2 seconds so that all ongoing animations can finish. I am attempting to implement a delay using setTimeout in Node.js. Here is what I have tried: this.userActivity = function(a,b, ...

How to iterate dynamically over arrays using JavaScript

I am working on a JavaScript project where I need to create a graph with 25 different data points. While my current JavaScript method is effective, I am facing an issue - I have multiple arrays and I am looking for a solution that allows me to use a for lo ...

In React production, the use of .map as a function is unavailable

While my express react app build runs smoothly locally with the map function, the transition to production triggers an error stating that 'map' is not a function. The error specifically points to the line declaring 'let returnlist'. Be ...

Guide to making a reusable AJAX function in JavaScript

Currently, I'm working on developing a function that utilizes AJAX to call data from another server and then processes the returned data using a callback. My goal is to be able to make multiple calls to different URLs and use the distinct responses in ...

Leverage the response data from the first AJAX call as a variable for the second

I have a script that performs two ajax calls - the second one is nested within the success handler of the first. However, I need to utilize the data retrieved in the first success handler as an additional variable to send in the second ajax call, and then ...

Leveraging "setState" in React Native with Promises

I am facing a challenge in updating the state of a React Component with data obtained from an API call. I encountered an issue where using the setState function within the promise resulted in an error "Type Error: _this2.setState is not a function" in Reac ...

JavaScript Time and Amount Formatting

My issue involves the formatting of returned data. I am looking to compile all values into a list with adjustments made to the time format and fare amount as indicated. Specifically, I need to remove commas from fare amounts and AM/PM from departure and ar ...

Incorporating the angular UI router effectively by reusing the same templateUrl and controller multiple times

Exploring the AngularUI Router framework for the first time, I am curious about how to enhance the code snippet below. Everything is functioning well at the moment, but as the project progresses, it will feature 20 questions or more. I want to avoid repea ...

Having Trouble with Axios PUT Request in React and Redux

I'm having trouble making a PUT request to the server. I understand that for a PUT request, you need an identifier (e.g id) for the resource and the payload to update with. This is where I'm running into difficulties. Within my form, I have thes ...

Implementing a NestJs application on a microcomputer like a Raspberry Pi or equivalent device

I'm facing a challenge in trying to find a solution for what seems like a simple task. I am aware that using the Nest CLI, I can utilize the command "nest build" to generate a dist folder containing the production files of my project. However, when I ...

What is the process for setting environment variables in a Svelte project?

I'm brand new to working with Svelte and I want to incorporate environment variables like base_url into different components. I've read that I can set up a store to hold these values, for example: const DataStore = writable([ { base_url: & ...

Is there a specific method or function that can effectively translate special characters such as into their corresponding representations?

When a user provides input for my script using shell arguments, it would look something like this: Kek kek\nkek\tkek\x43 After receiving the input, Javascript interprets my parameter in a specific way: var parameter="Kek kek\&bs ...

What is the method to retrieve response text?

This is the content of my register.js file: var formdata = new FormData(); formdata.append("name", name.value); formdata.append("username", username.value); formdata.append("email", email.value); formdata.append("password", password.value) ...

Having trouble implementing styles for an element selected using the document.getElementsByClassName() method

In order to adjust the style of a dropdown menu, I need to change its top value to align it properly. The element is being generated by Drupal (a CMS tool) and is configured with classes for styling purposes in the admin view where content is authored. How ...

Error: JSON data couldn't be processed due to an unexpected end, resulting in a SyntaxError at JSON.parse()

I'm currently working on making an ajax call to an API, but I keep encountering an error whenever I try to make the call. I've been troubleshooting this for hours and I can't seem to figure out what the issue is. At one point, I even removed ...

Having trouble with Vue.js image force download not functioning properly with anchor tags?

Currently, I am utilizing Laravel in conjunction with Vue.js. I have had the requirement to forcibly download an image on the browser, but unfortunately, it is not functioning as expected. var link = document.createElement('a'); link.href = &apo ...

Multiple minute delays are causing issues for the Cron server due to the use of setTimeout()

I have an active 'cron' server that is responsible for executing timed commands scheduled in the future. This server is dedicated solely to this task. On my personal laptop, everything runs smoothly and functions are executed on time. However, ...