a reliable approach to gain entry to properties that do not exist

Utilizing Google Apps Script along with JavaScript code, I am leveraging UrlFetchApp to retrieve data from the Stripe API in order to fetch an invoice. Subsequently, the Script processes the retrieved data and updates a Google Sheet template with it.

An issue that I am currently facing is that when the API does not contain information for a specific field related to a customer, the script encounters errors. The API indicates this absence of data as NULL; for instance, "discount": null might denote that a customer has no discount on the invoice.

Whenever the script encounters a line containing no data (NULL response), it breaks and ceases to execute further. My objective is to modify the behavior such that if there is no data available, the script should continue running and return a specified value denoting the absence of data (such as returning 0 for no discount) instead.

Here is the snippet of my code:

function getInvoiceObj() 
{
    var apiKey, content, options, response, secret, url;

    secret = "rk_live_xxxxxxxxxxxxxxxxxx";
    apiKey = "xxxxxxxxxxxxxxxxx";

    url = "https://api.stripe.com/v1/invoices/in_xxxxxxxxxxxxx?expand[]=charge&expand[]=customer";

    options = {
      "method" : "GET",
      "headers": {
        "Authorization": "Bearer " + secret 
      },
      "muteHttpExceptions": true
    };

    response = UrlFetchApp.fetch(url, options);

    //Push data to Sheet from invoice. **Overwrites existing Sheet data**
    content = JSON.parse(response.getContentText());
    var sheet = SpreadsheetApp.getActiveSheet();

    /* Customer Discount */
    sheet.getRange(21, 2).setValue([content.discount.coupon.percent_off]);
}

Answer №1

Are you in need of the if statement?

if(content.discount===null)
  sheet.getRange(21,2).setValue([0]);
else
  sheet.getRange(21,2).setValue([content.discount.coupon.percent_off]);

Maybe consider using ?:

sheet.getRange(21,2).setValue([
  content.discount===null?0:content.discount.coupon.percent_off
]);

Answer №2

This situation can be a bit complex and may remain relevant for years to come. The issue lies in the fact that coupon is not present within discount, making it impossible to retrieve any value from a nonexistent property, thus causing the script to break. However, there are several methods available to handle properties within non-existing objects:

  • Utilizing a try...catch structure

    try {
        sheet.getRange(21,2).setValue([content.discount.coupon.percent_off]);
    } catch() {
        sheet.getRange(21,2).setValue([0]);
    }
    
  • Implementing optional object passing

    const discountValue = ((content.discount || {}).coupon || {}).percent_off || 0;
    sheet.getRange(21,2).setValue([discountValue]);
    
  • Using nested existence checks

    const discountValue = (content.discount && content.discount.coupon && content.discount.coupon.percent_off) || 0;
    sheet.getRange(21,2).setValue([discountValue]);
    
  • Creating abstractions for property access

    const getPropertySafe = (props, object) => props.reduce((xs, x) => (xs && xs[x]) ? xs[x] : null, object)
    
    const value = getPropertySafe(['discount', 'coupon', 'percent_off'], content)
    sheet.getRange(21,2).setValue([value || 0]);
    

Anticipating the arrival of The Existential Operator at some point in the future

content.discount?.coupon?.percent_off || 0

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

Struggling to access specific data within a JSON object? Wondering how to extract and display data from a JSON object in VUE?

Despite my extensive searching on Stack and the internet, I have not been able to find a solution to my problem. Currently, I am attempting to retrieve data from a JSON file located in the Vue src folder. The file contains three arrays with names that inc ...

Ways to identify if a resize event was caused by the soft keyboard in a mobile browser

Many have debated the soft keyboard, but I am still searching for a suitable solution to my issue. I currently have a resize function like: $(window).resize(function() { ///do stuff }); My goal is to execute the 'stuff' in that function on ...

Update the button functionality according to the button's unique identifier

I am trying to dynamically change the button's redirect link based on its ID in my NEXT.JS project, but as a newcomer to this framework, I am unsure of how to accomplish it. I understand that this modification should be done after rendering, possibly ...

Encountering a problem with the mock object in Angular 11 unit testing when converting a JSON object to a TypeScript interface

Within my Angular 11 application, I am working with a JSON response and have defined an interface to match the structure of this JSON object. The JSON object looks like this: { "division": { "uid": "f5a10d90-60d6-4937-b917- ...

Unraveling the Mystery of jQuery Syntax

Upon reviewing jquery.ui-1.8.11.js: $.extend(Datepicker.prototype, { /* A unique class name appended to elements indicating they are configured with a date picker. */ markerClassName: 'hasDatepicker', /* For debugging purposes (if e ...

Encountering difficulties importing in Typescript and ts-node node scripts, regardless of configuration or package type

I am facing a challenge with my React Typescript project where multiple files share a similar structure but have differences at certain points. To avoid manually copying and pasting files and making changes, I decided to create a Node script that automates ...

Tips for switching out images depending on the time of day

Currently, I have a script that dynamically changes the background color of my webpage based on the time of day. However, I am facing issues trying to implement a similar functionality for replacing an image source. The current code is also time zone-based ...

Unspecified origins of Js in Chrome Extension

console.log(chrome.runtime.sendMessage({from:"script2",message:"hello!"})); However, attempting to send the message from a background script to a content script is proving to be unsuccessful. https://i.stack.imgur.com/ERgJB.png ...

Leveraging the node CLI tool as a library for trimming MP3 files (trimp3

I recently came across a fantastic library that I am interested in using for my nodejs project: https://github.com/kyr0/trimp3 The only issue is that it functions as a cli tool, and I would like to integrate it seamlessly into my codebase as a library. D ...

My Special Character is not encoded by JSON

Within my database table, there are two fields present: Title = Testing Title Description = CREDITO FISCAL OCDE CFDI AMPAROS REVISIÓN ELECTRÓNICA REGLAMENTO ISR RIF ID: 44 However, when I receive the json response, it always returns with a null descrip ...

There is an issue with the functionality of Java code that has been adapted from Javascript logic

I'm currently using NetBeans8 IDE. Check out this java script function from this Fiddle function animate() { xnow = parseInt(item.style.left); item.style.left = (xnow+1)+'px'; ynow = parseInt(item.style.top); item.style. ...

Calling a C# Webmethod using jQuery AJAX is not working as expected

I'm currently facing an issue calling a web method that I created. The problem lies in the fact that the ajax call isn't reaching my web method, which is puzzling to me because I have another web method in the same file with the same return type ...

Guide on How to Retrieve the Following YouTube Video using a PHP Array

I have a PHP/HTML script that currently loads a random YouTube video from an array every time the page is refreshed. However, I am looking to add functionality for next and previous buttons to allow users to cycle through the videos in the array. The goal ...

How can Node.js and Express be used to conceal Javascript code on the backend?

I'm a beginner when it comes to Node and Express. I have a query regarding how to securely hide Javascript code on the backend. Currently, I am working with Node.js and Express. My goal is to prevent users from easily accessing the code through browse ...

Learn the process of merging queries from two tables and grouping them into a JSON Array on a WCF Service

I have two tables in my SQL Server Database and I would like to combine them into a single JSON Array within my WCF Service. Table1: ---------------- | type | total | ---------------- | A | 2 | | B | 3 | | C | 4 | ---------------- T ...

Transform a json-like string (not in JSON format) into an object using Java

I am working with a string that looks like this: {InstanceStatuses: [{AvailabilityZone: us-east-2b,Events: [],InstanceId: i-79e234fd, InstanceState: {Code: 16,Name: running},InstanceStatus: {Details: [{Name: reachability,Status: initializing}],Status: ini ...

What is the best way to separate axios functions and components in Vue3?

In my opinion, it's more efficient to separate the axios commands from the vue components. This is how I structured my directories: src api - products.js components - Products.vue products.js import axios from 'axios'; const li ...

The Server Components render encountered a glitch

Screenshot of the errorI am encountering a strange error only in the production environment. The lack of additional information leads me to believe it may be due to security measures put in place for production. Unfortunately, I have been unable to repli ...

I attempted to implement an AJAX function, but unfortunately, it is not displaying any output

I attempted to implement an AJAX function but the output is not displaying anything. var ajaxFunction = function(url, method, data = "") { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { ...

Is there a way to transform a large gltf file into jsx format?

I recently created a 3D scene in Blender and wanted to incorporate it into my React Three Fiber project. However, after exporting the scene to glTF format, I discovered that the file contained around 300k lines. The strange thing is that the file works per ...