Unable to retrieve this information within an anonymous function

I am currently working on converting the JSON data received from an API interface into separate arrays containing specific objects. The object type is specified as a variable in the interface.

Here is the interface structure:

export interface Interface{
  interfaceClassType: string;
}

The method to retrieve JSON data is as follows:

getJSON(): Observable<Interface[]> {
    return this.http.get<Interface[]>(URL)
      .pipe(
        retry(2),
        catchError(this.handleError)
      );
  }

To implement this, I have created the following code:

arrayWithObjects: Interface[];
 class1Array: Class1[];
 class2Array: Class2[];

 processJSON(): void {
    this.configService.getJSON().subscribe(results => this.arrayWithObjects = results);
    this.arrayWithObjects.forEach (function (object) {
      switch (object.interfaceClassType) {
        case "first":
          this.class1Array.push(object as Class1);
          break;
        case "second":
          this.class2Array.push(object as Class2);
          break;
      }
    }.bind(this))
  }

Even though the above implementation seems correct, calling it triggers an error message:

ERROR TypeError: this.class1Array is undefined

Answer №1

Two important points need to be addressed in this scenario.

  1. this.arrayWithObjects is assigned asynchronously, so when you try to use forEach, it may not be assigned yet. To fix this issue, consider moving the forEach inside the subscription block.
processJSON(): void {
  this.configService.getJSON().subscribe(results => {
    this.arrayWithObjects = results;
    this.arrayWithObjects.forEach (
      ...
    );
}

For more information on handling asynchronous data, visit this resource.

  1. Instead of using conventional JS function, switch to arrow function notation to correctly reference class member variables with the this keyword. In a regular JS function, this refers to the function's scope rather than the class context.
processJSON(): void {
  this.configService.getJSON().subscribe(results => {
    this.arrayWithObjects = results;
    this.arrayWithObjects.forEach((object) => {       // <-- apply arrow function here
      switch (object.interfaceClassType) {
        case "first":
          this.class1Array.push(object as Class1);
          break;
        case "second":
          this.class2Array.push(object as Class2);
          break;
      }
    });               // <-- no need for `bind()` method
  });
}

Answer №2

When you utilize a standard function as a callback, it does not maintain the scope of this within it. However, employing an arrow function resolves this issue.

this.arrayWithObjects.forEach ((object) => {
      console.log(this.class1Array);
})

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

Could json.loads() be exploited for executing arbitrary code?

Does the json.loads function from Python's built-in json module pose any risk of allowing arbitrary code execution or other security vulnerabilities? I need to process JSON data from sources that may not be trustworthy. ...

Can you explain the functionality of this JSON Decoder script?

For a while now, I've been working with the following code: def read_text_files(filename): # Setting up JSON Decoder decoder = json.JSONDecoder() with open(filename, 'r') as inputfile: # Processing next item in input fil ...

Exploring the world of dynamic locale with Angular 5 Pipes

My current situation involves having apps created in angular 4 and I am contemplating upgrading to angular 5. After researching how locale is managed in the pipes, it appears that upgrading may not be feasible. It seems that there are two options provided: ...

Converting JSON to CSV with flexible array lengths: Harnessing the power of jq

I have retrieved a JSON data with the given structure { "type": "conversation", "id": "1234", "created_at": 1425586662, "initial_message": { "type": "initial_message", "id": "567", "body": "<p>Testing</p> ...

Writing to Json files in Azure Data Factory

Can I get your thoughts on this? So, working in Azure Data Factory, I have a series of activities that generate a JSON segment at the end of each run {"name":"myName", "email":"<a href="/cdn-cgi/l/email-protection" cla ...

Is it possible to retrieve various nested json properties in kusto (KQL)?

I am receiving telemetry events sent to Playfab. Within these events, I need to extract the content of the Payload. Currently, I am able to retrieve all information from my event except for the SuperProperties nested within the Payload. The issue is that a ...

Mac JSON Shell Scripting

Below is the code I am struggling with: function poke() { json="curl -s -X GET http://pokeapi.co/api/v2/type/bug.json"; prop="half_damage_to" temp=echo $json | sed 's/\\\\\//\//g' | sed 's/[{}]//g& ...

What is the best method for extracting individual JSON objects from a response object and presenting them in a table using Angular?

After receiving a JSON Array as a response Object from my Java application, I aim to extract each object and display it on the corresponding HTML page using TypeScript in Angular. list-user.component.ts import { HttpClient } from '@angular/common/h ...

Looping through an array of nested objects using Vue

I have encountered a challenge with accessing specific data within an array that I am iterating over. The array is structured as follows, using Vue.js: companies: [ name: "company1" id: 1 type: "finance" additionalData: "{& ...

retrieving attribute values from JSON objects using JavaScript

I am struggling to extract certain attribute values from a JSON output and use them as input for a function in JavaScript. I need assistance with this task! Below is the JSON data that I want to work with, specifically aiming to extract the filename valu ...

Tracking the real-time location of multiple markers on Google Maps using the Android platform

I'm currently working on developing a map that displays the locations of specific individuals on the Google Map. To achieve this, I've set up a web server with a MySQL database. Whenever the android app is active, it saves the user's current ...

What could be the reason for typescript not issuing a warning regarding the return type in this specific function?

For instance, there is an onClick event handler attached to a <div> element. The handler function is supposed to return a value of type React.MouseEventHandler<HTMLDivElement> | undefined. Surprisingly, even if I return a boolean value of fal ...

Error in React Native Navigation: Passing parameters is not functioning properly

Within my React Native application, I have meticulously established the following routes in my app.js: export default class App extends Component { render() { return ( <NavigationContainer> <Stack.Navigator initialRouteName=&qu ...

How do I loop through each object within an observable that contains an array of objects in Angular 2?

Hey everyone! I'm currently in the process of upgrading my skills to Angular 2 and I have a few questions. One of them being, how can I iterate through each object in an observable array object? I was able to successfully retrieve data from "api/v1/e ...

When using Python to write data to a file and then retrieving it with JSON, the returned result

I've encountered an issue while trying to save data to a file using the code snippet below #!/usr/bin/python37all print('Content-type: text/html\n\n') import cgi from Alarm import * import json htmldata = cgi.FieldStorage() alarm_ ...

Here's the step-by-step process: Access the specific item in the object by referencing `obj[i]["name of desired attribute"]

I tried seeking advice and consulting multiple sources but none provided a suitable answer. Is there someone out there who can assist me? obj[i].["name of thing in object"] Here's the array: [ { "name": "DISBOARD#2760" ...

Developing dynamic-sized tuples in TypeScript

Recently, I was attempting to develop a zipper for arrays. For instance, if the user inputs 3 arrays with sizes of 3, 5, and 12, the output array of tuples would be the size of the largest array. The output consists of tuples containing elements at a speci ...

Stop users from logging in simultaneously on multiple systems

It is possible for the same user and password to be used on multiple computers simultaneously! If person 1 is logged in with a certain username and person 2 logs in from another computer or browser using the same credentials, person 1 will not be automatic ...

What is the best way to save the result of an API request as an object or convert an array into JSON format?

My app is attempting to make an API call and display the retrieved data in a modal. The issue lies in storing the API response as an array, which prevents me from accessing its sub-elements effectively. My query is: Is there a way to either: Save an obje ...

Tips for preserving axois GET response as a JSON object or in its original form upon arrival

export class LoadProfile extends Component { state = { data: '' } componentDidMount() { axios({ url: 'http://localhost:8080/profile/all', method: 'GET', responseType: 'json', ...