The property length is undefined and cannot be read

I'm currently utilizing a dexi.io robot for the purpose of automating data extraction from permit databases. This particular robot has the capability to process custom JavaScript in order to dissect the incoming JSON object.

While this code does function correctly at times, successfully parsing the incoming JSON, it unfortunately fails to operate effectively in nearly all scenarios. An error message stating "cannot read property of length undefined" frequently appears.

If you'd like to test out the API that is functioning properly, click on the following link:

Below is the JavaScript code being used:

var people = JSON.parse(json).value;
var arr = [];

function getCountry(member) {
    try {
        return member.fields.name;
    } catch(err) {
        return "";
        }
}

for (i = 0; i < people.length; i++) {
    var member = people[i];
    var obj = 
        {
            "name": member.name,
            "Country": getCountry(member),
            "alias": member.alias
            };
    arr.push(obj);
}

return arr;

Answer №1

Make sure to review the initial line for the presence of "json". It seems like you may have overlooked defining a json file that is used to retrieve data.

Answer №2

If you're unsure about the process of fetching a response, I managed to make it work quite easily by following these steps:

fetch("https://services.odata.org/V4/TripPinService/People")
.then(response => response.json())
.then(data => {
  var people = data.value;
  var arr = [];
  function getCountry(member) {
      try {
          return member.AddressInfo[0].City.CountryRegion;
      } catch(err) {
          return "Country Info Not Available";
          }
  }
  
  for (i = 0; i < people.length; i++) {
      var member = people[i];
      var obj = 
          {
              "name": member.FirstName,
              "Country": getCountry(member),
              "alias": member.alias
              };
      arr.push(obj);
  }
  
  console.log(arr);
});

This method might inspire some innovation in your project.

Answer №3

After examining the json data from the provided URL, I noticed that in your code, properties such as 'member.name', 'member.alias', and 'member.fields.name' do not actually exist. I recommend using the precise property names as they appear in the json:

{
  "@odata.context": "http://services.odata.org/V4/TripPinService/$metadata#People",
  "@odata.nextLink": "https://services.odata.org/V4/TripPinService/People?%24skiptoken=8",
  "value": [
    {
      "@odata.id": "http://services.odata.org/V4/TripPinService/People('russellwhyte')",
      "@odata.etag": "W/\"08D817F8EC7DAC16\"",
      "@odata.editLink": "http://services.odata.org/V4/TripPinService/People('russellwhyte')",
      "UserName": "russellwhyte",
      "FirstName": "Russell",
      "LastName": "Whyte",
      "Emails": [
        "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83d1f6f0f0e6efefc3e6fbe2eef3efe6ade0ecee">[email protected]</a>",
        "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7725020404121b1b37141819031804185914181a">[email protected]</a>"
      ],
      "AddressInfo": [
        {
          "Address": "187 Suffolk Ln.",
          "City": {
            "CountryRegion": "United States",
            "Name": "Boise",
            "Region": "ID"
          }
        }
      ],
      "Gender": "Male",
      "Concurrency": 637285705159912400
    }
  ]
}

In essence, make sure to use the exact property names from the json data like 'member.UserName', 'member.AddressInfo[0].Name', etc.

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

Asynchronous data fetching with React Hook useEffect does not properly populate the tooltip in Material UI component

After using useEffect to fetch data, I encountered a problem in passing the data to my component. Here is some of my code: User Data Types (UPDATED) export interface IUser { display_name: string; id: string; images: Image[]; } expo ...

Exploring Checkbox Limiting with jQuery

Is there a more efficient approach to restrict the selection of checkboxes? I want the script to be adaptable depending on the applied class, which will always indicate the maximum allowed value (e.g., "limit_1" or "limit_2"). Currently, I'm creatin ...

Displaying incorrect data with AngularJS

I have encountered a view issue while using AngularJs. Below is my code along with the outcome. Any assistance on this matter would be highly appreciated. .service("SubjectService", function ($http, $q) { var deferred = $q.defer(); $http.get(&apo ...

Switch between selecting every group of 3 items and every group of 4 items

Having an array with more than 14 items, I need to group them into 2 different groups in this specific way: The first 3 (#1,2,3) will be in array A, the next 4 (#4,5,6,7) will be in array B, the following 3 (#8,9,10) will be in array A, the subsequent 4 (# ...

Synchronize data with Microsoft AJAX using force sync

When working with the Microsoft AJAX framework, I encounter a problem where my AJAX calls are asynchronous when I actually need them to be synchronous. I'm struggling to find a solution for this issue. In addition, I have been having difficulty findi ...

Deliver a response to recipients through the "button" feature within the WhatsApp cloud API

I'm working on building a chatbot for my booking company. Here is an outline of my initial bot flow: const axios = require("axios").default; function initialize_bot(message, phone_number, access_token, sender, username) { if (message === ...

Initiating and handling a POST request

In my node.js server, I have a simple setup like this: var express = require('express'); var app = express(); app.post('/savearticles', function (req, res) { res.send(req.body); }); Additionally, the javascript code is not very c ...

PHP code saves empty value to JSON file

MODIFIED Issue - After executing the function, a null value is written to the JSON file. Expectation - Gather information inputted into an HTML form and add it to an existing JSON file. Here are some of the resources from Stack that I've referenced ...

I am attempting to secure a webpage with a password using JavaScript

I've been working on adding password protection to my webpage at , with the goal of allowing users to enter the password once per session. However, I've encountered an issue: if a user cancels out of the initial prompt or enters the wrong passwor ...

Exploring ways to retrieve JsonData from a provided image

Array product model view model details Here is my code snippet: productDetailsNameLabel.text = products[indexPath.section].arr_details?[indexPath.item].productname An error message is being displayed: The type 'Arr_Details' does not have a ...

Dealing with illegal characters, such as the notorious £ symbol, in JSON data within a JQuery

I'm encountering an issue with a textarea and the handling of special symbols. Specifically, when I use $('#mytextarea').val() to retrieve text that contains '£', I end up seeing the black diamond with a question mark inside it. T ...

Construct Hashtable using JSON data

Is there a way to accurately serialize a Hashtable into JSON format? @{Path="C:\temp"; Filter="*.js"} Using ConvertTo-Json leads to this result: { "Path": "C:\\temp", "Filter": "*.js" } However, when trying to convert the JSON ...

What is the best way to insert an HTML attribute into a dynamically generated build script within Angular?

After running the ng build --prod command, Angular creates 4 scripts. One of these is called main.js. I am wondering if there is a way to dynamically add an HTML attribute to this script tag in the index.html file once the build process is complete. I nee ...

The x-axis title in Apexcharts is consistently misaligned

Dealing with some issues regarding the placement of the x-axis title in my column chart. The position of the title seems to vary based on the y-values range, as illustrated in these examples: Example 1 Example 2 Below is the code I am using: Code block ...

The JSON response needs to be transformed from a single line into a Dataframe format

Implementing the TDAmeritrade API. This is how I made the request: urlData = requests.get(url = endpoint).content Upon requesting Option Chain data, the output is a single extended JSON string. {'symbol': 'AAN', 'status': &a ...

I'm looking for a way to create a Redux thunk action creator that will return a promise. How

In my code, I have a primary thunk that is triggered by a button click. Within this thunk, I need to invoke another thunk and ensure it completes before proceeding. The second thunk returns a promise. Below is an excerpt of the code in question: export f ...

Tips for handling the accent mark (diacritic mark)

My primary language is Spanish, which means I use accent marks quite frequently (á, é...). When I need to type them out, I resort to using &aacute;, &eacute;, and so on. However, I'm facing an issue when trying to compare two sentences in m ...

Ways to refresh the DOM while making an asynchronous request

Consider the following async function: async function predict_from_model() { $("#loading").html("first update") const model = await tf.loadModel('model.json'); $("#loading").html("second update") //delayed for (var i = 0; i < 100; i++ ...

Managing two simultaneous web service calls in Angular 2

Dealing with two parallel web service calls can be tricky. Sometimes the first call goes through first, and other times it's the second one. The problem arises when the function in my second service requires data from the first service call. I attemp ...

Different ways to modify the CSS file of the bx-slider plugin for multiple sliders within a single webpage

Currently in the process of building a website using bx slider. I am looking to incorporate three sliders onto a single page for sliding HTML content. Initially, I added a bx slider to the page and customized it using CSS. I made modifications within jqu ...