Looping through the json resulted in receiving a null value

When working with typescript/javascript, I encountered an issue while trying to fetch the 'statute' from a data object:

{_id: "31ad2", x: 21.29, y: -157.81, law: "290-11",....}

I attempted to assign data.law to a variable, but received a typeerror stating that it cannot read property 'law' of undefined?

Strangely, when I console log 'data.law' at line 11 or result[0] at line 18, the correct value is displayed...

sectionsSuccess(res: Response) {
  this.allSections = [];
    this.sections = [];
    this.loadingSections = false;
    try {
      let jsonRes = res.json();
      this.jsonResLength = jsonRes.length;
      for (var a = 0; a < this.jsonResLength; a++) {
        let js = jsonRes[a];
        js.bookmarked = this.server.isInBookmark(js);
        this.allSections.push(js);
        if (a < 15) {
          this.sections[a] = this.allSections[a];
        }
      }
    } catch (e) {
      alert("Exception: " + e.message);
    }

    for (var i = 0; i < this.allSections.length; i++) {
      this.allSections[i] = this.convertLocationDataToStatutes(this.allSections[i]);
    }
// complete code added above
  for (var i = 0; i < this.sections.length; i++) {
    this.sections[i] = this.convertLocationDataToStatutes(this.sections[i]);
  }
}
  convertLocationDataToStatutes(data: any): any {
    var self = this;
    var chapterandsection = data.law; //line 11
    var values = chapterandsection.split('-');
    var chapter = values[0];
    var section = values[1];
    (self.server).getSection(chapter, section)
      .map(response => response.json()).subscribe(result => {
      return result[0];  // line 18
    });
  }

Answer №1

It seems like the function convertLocationDataToStatutes is not returning any value, yet its return value is being used in your code. When a function does not return anything, it is considered as undefined. As a result, the loop is populating this.sections with multiple instances of undefined. This leads to an error when sectionsSuccess is called again, as accessing data.law on this.sections[x] will result in an error due to the undefined values. The issue is most likely occurring during the second call of sectionsSuccess, while the first time you logged data.law was during the initial call.

The only return statement in convertLocationDataToStatutes appears to be within the subscribe callback. It is possible that you intended to have a return statement within the convertLocationDataToStatutes function itself.

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

Template is not populating with data (Angular)

Currently, I am honing my Angular skills by working on a simple project. I have been seeking answers to my queries on Stack Overflow as they closely align with the issue I am facing. My challenge lies in displaying asynchronous data before it is initialize ...

JavaScript code snippet to remove a specific element from an array and store it in an object

I am looking to convert an array into an object, where each item in the array is separated into categories as shown below. let a=['monkey: animal','John:human', 'Rob:human', 'donkey:animal'] I expect the output to b ...

Improved method for linking two enums with similar appearances

Currently, I use two enums as shown: enum Tab { Approved = "Approved", Pending = "Pending", Sold = "Sold", } enum ProductStatus { Approved = "Approved", Pending = "Pending", Sold = "Sold&q ...

PHP's json_encode function does not escape the single quote character

I am currently facing an issue with parsing a JSON encoded object in JavaScript. When I use JSON.parse(word_array);, it throws an error saying Uncaught SyntaxError: Unexpected identifier. Upon investigating, I discovered that the object word_array is miss ...

execute the function once the filereader has completed reading the files

submitTCtoDB(updateTagForm:any){ for(let i=0;i<this.selectedFileList.length;i++){ let file=this.selectedFileList[i]; this.readFile(file, function(selectedFileList) { this.submitTC(updateTagForm,selectedFileList); }); } } } ...

Encountering an issue in Angular 4 AOT Compilation when trying to load a Dynamic Component: Error message states that the

My Angular application is facing challenges when loading dynamic components. Everything works smoothly with the JIT ng serve or ng build compilation. Even with AOT ng serve --prod or ng build --prod, I can still successfully build the application. Lazy loa ...

Attempting to crack the code within body-parser and Node.js

I am just getting started with Node.js & Express and trying to follow a tutorial at https://github.com/jw84/messenger-bot-tutorial. I have a good understanding of most parts, but I'm confused about the use of "entry" and "messaging" in this code snipp ...

Why is the Twitch api map function returning nothing, while the console log is showing output?

Presently, my Nextjs page is making multiple Twitch API calls successfully and displaying the correct data. However, one of the mapping functions is failing to render anything on the page, even though the console log shows the data. Although I am relativel ...

Displaying svg files conditionally in a react native application

I have developed an app specifically for trading dogs. Each dog breed in my app is associated with its own unique svg file, which are all stored in the assets folder (approximately 150 svg files in total). When retrieving post data from the backend, I re ...

Exploring paths deep within by employing wildcards as a query

I have data structured according to Firebase's flat structure advice, storing quotes in nodes like this: quotes -> clientName -> quoteObject Each 'quoteObject' includes a 'dateCreated' value that I aim to retrieve as follow ...

Top method for troubleshooting JavaScript code in Visual Studio 2010

Is there a way to troubleshoot JavaScript code in Visual Studio 2010 for MVC Razor projects? ...

Symfony along with React router have encountered an error: route not found

In my current project, I am working with Symfony3 and integrating React.js along with react-router to create a bundle. One issue I have encountered is that when using the routing in React, if I refresh the page, the Symfony routing module displays 'N ...

Tips for fixing flickering tables and bringing the scrollbar back to the top in your DataTable Forge viewer

Presently, I am working with a DataTable that consists of 100 rows and is being set up using lists. The lists dynamically change based on the selected name from a drop down. To achieve this, I use: $("#datatable").remove(); this.datatable = new Au ...

"Want to know the best way to retrieve the most recent form input value using jQuery or Javascript

I've been reading a lot about using jQuery to set and get field values, but I'm encountering an issue where I can't retrieve the value after submitting, editing it in an input field, and then submitting again. It works the first time, but no ...

What causes a Typescript error when attempting to escape a newline character?

My approach is quite simple: I concatenate multiple strings and format them to make them more readable. info() { return "x: " + this.xpos.toString() + "\n" \ + "y: " + this.ypos.t ...

Automatic Clicks in the Chrome Console

I've come across a website that requires me to click on multiple elements scattered throughout the page Here is the code for one of the elements: <span class="icon icon-arrow-2"></span> Is there a way to provide me with the console comm ...

Adjusting the value of a user form with multidata in PHP and Javascript

I am looking for guidance on how to modify the value of an input in a form that contains multiple data entries. Here is my form: <form method="post" action="pax-flight.php#pax-flight" class="paxform"> <input type="hidden" value="{"data":{"us ...

Bringing in a variable from a React component to a JavaScript file

I've created a React component called Button with two states named name and players. Now, I need to access these states in a separate JavaScript file that is not a component. Below are the relevant code snippets: Button.js import {useState} from &qu ...

Is there a way to delete a stylesheet if I only have limited information about the url?

I am attempting to dynamically remove a CSS stylesheet using JavaScript or jQuery. I am aware that the target stylesheet is located within the 'head' element and includes the text 'civicrm.css', however, I do not possess the full URL o ...

What is the best way to reduce the file size of a group of PNG images for

For my game character, I have a collection of PNG files including stand.png, run1.png, run2.png. To display a series of actions on the JavaScript canvas, I need to load these images. However, the size of each .png file adds up quickly – for example, it ...