Employing JavaScript to retrieve data from an array

Currently, I am retrieving JSON data from an API source and preparing to store it in an array within Google Sheets. To format the data correctly, I have utilized JSON.parse, resulting in the following structure:

[{EmployeeRef={name=value, value=value}, NameOf=value, Hours=value, TxnDate=value, HourlyRate=value, Minutes=value, PayrollItemRef=value, SyncToken=value, BillableStatus=value, sparse=value, MetaData={CreateTime=value, LastUpdatedTime=value}, domain=value, ItemRef={name=value, value=value}, ID=value, CustomerRef={name=value, value=value}, Taxable=value}, etc.]

However, I encounter an error when attempting to push this formatted data into the designated empty array. Below is the code snippet being used for this purpose:

results.forEach(function(elem,z) {
    output.push([elem["TxnDate"], elem["EmployeeRef"]['name'], elem["CustomerRef"]['name'], elem["ItemRef"]['name'], elem["BillableStatus"], elem["HourlyRate"], elem["Hours"], elem["Minutes"], elem["Description"]]);
  });

The specific error message received is as follows:

"TypeError: Cannot read property "name" from undefined. (line 62, file "Code")".

To investigate further, I attempted to extract a set of values from the array with the following line of code:

Logger.log(results[0]['EmployeeRef']['name']);

This resulted in:

[18-12-06 13:27:41:465 EST] value

[18-12-06 13:27:41:878 EST] value

What is puzzling is why two values are returned in this instance. I initially expected results[0] to return one 'row' from the array, but it appears to be a combination of 'EmployeeRef' and 'name' values from both results[0] and results[1].

Could this issue be the cause of the TypeError message? Any insights on what might be going wrong here?

Answer №1

One issue you are encountering is the absence of the CustomerRef object within your array of objects. This is causing the error when attempting to add elem["CustomerRef"]['name'] to the array.

(Please note that this problem is not related to the presence of EmployeeRef)

To resolve this, consider implementing a check for null before accessing the name parameter of inner objects in your array. Here's an example:

results.forEach(function(elem, z) {
    output.push(
        [elem["TxnDate"],
         elem["EmployeeRef"] ? elem["EmployeeRef"]["name"] : null,
         elem["CustomerRef"] ? elem["CustomerRef"]["name"] : null,
         elem["ItemRef"] ? elem["ItemRef"]["name"] : null,
         elem["BillableStatus"],
         elem["HourlyRate"],
         elem["Hours"],
         elem["Minutes"],
         elem["Description"]
    ]);
});

Note: By including these null checks, you can avoid errors and populate your array with null values if either the EmployeeRef or CustomerRef objects do not exist.

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

Deliver the message at the perfect moment

Here's the situation ... I'm trying to figure out how to make a specific action happen every day at a set time using my code. Since I am currently learning JavaScript, I think I need to incorporate some kind of loop (although I'm not entire ...

Decoding JSON with C# to interpret an array of regular expressions

I have an array of regular expression patterns stored in a single field within a database in a JSON-like format. The structure looks like this: ["^.*\/Car($|\/$|\?|\/\?)"] https://i.sstatic.net/faooM.png I am attempting ...

Converting a JavaScript function to work in TypeScript: a step-by-step guide

When writing it like this, using the this keyword is not possible. LoadDrawing(drawing_name) { this.glg.LoadWidgetFromURL(drawing_name, null, this.LoadCB,drawing_name); } LoadCB(drawing, drawing_name) { if (drawing == null) { return; ...

What is the best way to fetch information in AngularJS using $http from a URL that does not have an explicit file extension (such as .json or

Attempting to retrieve data from the given link: Upon accessing the link, it appears as a JSON file format. I can confirm the accuracy of the data, as I saved it locally in .json format and successfully retrieved it using an $http request. The question n ...

Error 19: Constraint violation - duplicate entry detected

While trying to set up my app, create a local database, and insert the very first user who has logged in locally, I encountered an error message at a specific point in the code. Here's where it happened: angular.module("greenApp") .service("d ...

Filter an array containing objects within objects and use the reduce method to calculate the total value

Here is an array of objects that I'm working with: const data = [ { "order_id":38795, "order_type":"Music", "date":"2021-08-14", "name":"Concert ...

Dealing with timeouts in getJSON requests

When using the jQuery getJSON() function, data is retrieved smoothly most of the time. However, there are instances where the loading process seems to be stuck, displaying "loading loading loadin" at the center of the page. While the ajax() function has ...

Dynamic Autocomplete Text Input featuring API-supplied Array in Angular

Currently, I am exploring the process of populating a text box with user emails obtained through an API call to the server. select-users.component.html: <input type="text" placeholder="Email Search" aria-label="Email" matInput [form ...

Making certain parts of a select list text bold while keeping others in normal font in React

I need to create a select list that displays various products with their names and a count in bold. Here's my approach: To achieve this, I am populating an array called productInformation with each product name and its corresponding count like this: ...

Tips for creating a Vue component that triggers the select dropdown to open when the entire div or wrapper is clicked

I have a custom-designed select dropdown with unique symbols for the select arrow. To achieve this look, I've hidden the default select arrow/triangle and placed our symbol on top as an image file. <div class="select-wrapper"> < ...

Extracting data from the web using PHP

I'm facing an issue with my code that scrapes data from a website. The current output looks like this: Agriculture Food Apparel I want to only display the first/nth category, for example just "Agriculture". I attempted: echo $sub_title[1].&ap ...

Creating Graphs for Dynamic JSON Data in Python

The JSON Graph Data I am working with does not have set keys and returns data for the last 180 days. The information consists of millisecond timestamps as keys and in-game prices as values. To effectively parse this data, I need to figure out a method to c ...

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 ...

Rails - Passing JSON data to controller results in an evaluation of nil

When trying to pass a JSON as a parameter to a controller in my Rails app, I keep encountering errors indicating that the parameter is null. The JSON is generated from user input on a view and sent to the controller by clicking on the #summary element lik ...

Creating a submenu within the sidebar component in Next.js

Is there a way to loop and display the subMenu on the sidebar component, but instead of showing up under the parent menu, it should appear on the right side of the parent menu as shown in the image below: https://i.sstatic.net/csdnC.png Below is the code ...

Font size for the PayPal login button

I am looking to adjust the font size of the PayPal Login button in order to make it smaller. However, it appears that the CSS generated by a script at the bottom of the head is overriding my changes. The button itself is created by another script which als ...

Enable my textbox to interpret the html img tag

Is there a way to display emoji images instead of emoji symbols when inserting them into my textbox? For example, can I show the image representation of ':)' instead of just the symbol itself? ...

What is the specific table element compatible with Polymer3?

I stumbled upon iron-data-table (), but it relies on bower which is used in Polymer2. However, I am working with npm in Polymer3. Is there a suitable table element or an alternative solution compatible with Polymer3? ...

Trigger event when user ceases to click

I have successfully implemented a click event using jQuery. Here is the code: $('#myButton').click(function(){ // perform desired actions }); However, I am facing an issue where multiple intermediate events are triggered if the user clicks on ...

Model implementation in Django as a component of an Ajax response

Currently in my views.py, I have a Django model that I want to include in the response for my Ajax request: def get_account(request, account_id): try: account = Account.objects.get(pk=account_id) success = True error_message = ...