Utilizing Typescript to transform a JSON object into a Typescript class

Hi there, I am facing a challenge while trying to convert an array of JSON objects into a TypeScript class. Every time I try to assign a JSON object attribute to a TypeScript attribute, the method crashes.

Here is the TypeScript interface I am working with:

export interface marker {
    lat: number;
    lng: number;
}

Below is the TypeScript method in question:

public markers: marker[];

ngOnInit() {
    this.mapService.GetPhotosById(this.id).subscribe(resultlisting => {
        this.values = resultlisting;
        console.log(this.values);
        this.ChangetoMarkers(this.values);
    }, error => this.errorMessage = error);
}

ChangetoMarkers(someArray: Observable<any[]>) {

    for (let entry of someArray) {
        let mark: marker;
        mark.lat = Number(entry.latitude); 
        mark.lng = +entry.longitude; 
        this.markers.push(mark);
    };
    console.log(this.markers); 
}

Next up, the Map Service implementation:

GetPhotosById(id: string): Observable<any> {
    return this.http
        .post(this.config.apiEndpoint + "mapPhotos/" + id)
        .map(this.extractJson).catch(this.handleErrors);

};
private extractJson(res: Response) {
    let data = res.json();
    return data;
}
private handleErrors(error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
        const body = error.json() || '';
        const err = body.error || JSON.stringify(body);
        errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
        errMsg = error.message ? error.message : error.toString();
    }
    console.log(errMsg);
    return Observable.throw(errMsg);
}

I have tried applying integer casting but it hasn't resolved the issue. Any help or suggestions would be highly appreciated.

Answer №1

In the discussion by Mauricio Poppe, it was pointed out that you are attempting to access properties of a variable that is undefined.

convertToMarkers(points: Array<{latitude: number, longitude: number}>) {
  this.markers = entries.map(({latitude: lat, longitude: lng}) => ({
    lat,
    lng
  }));

  console.log(this.markers);
}

No conversion of numbers is needed as the latitude and longitude values are already in numeric format after deserialization.

Answer №2

Here's a possible solution to your issue:

ConvertToMarkers(someArray: any[]) {
    console.log("array",someArray);
    for (let entry of someArray) {
        let markerPos: marker = {lat: entry.latitude, lng: entry.longitude};
        console.log("marker position", markerPos);
        this.markers.push(markerPos);
    };
    console.log("markers array",this.markers); 
}

This code may not be as sophisticated as Aluan Haddad's solution, but it should help you pinpoint where the problem lies by logging the array before the loop, individual markers before adding them to the list, and the final list 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

Version 2.0.0 of Angular working with Karma to offer Router capabilities

When a test requires an instance of the `Router`, simply providing the `Router` itself is not sufficient: import {Router} from '@angular/router'; import {it, inject, beforeEachProviders} from '@angular/core/testing'; import {Compo ...

Exploring the inner workings of view encapsulation in Angular

It is common knowledge that the default view encapsulation for a component in an Angular application is Emulated. encapsulation: ViewEncapsulation.Emulated I am quite perplexed about how it functions without being a shadow DOM. ...

Make cards disappear with a sleek scrolling effect in Angular (I'm open to library recommendations)

I want the cards to appear on the screen as I scroll. My knowledge of angular animation is limited, but I have used it for now. html: <div class="row" *ngIf="posts"> <div id="feed-{{post.id}}" (click)="getFeed(post)" *ngFor="let post of posts ...

Encountering a "Duplicate identifier error" when transitioning TypeScript code to JavaScript

I'm currently using VSCode for working with TypeScript, and I've encountered an issue while compiling to JavaScript. The problem arises when the IDE notifies me that certain elements - like classes or variables - are duplicates. This duplication ...

Are there any recommended boilerplate templates for a Typescript + Nodejs server setup?

I am currently in the process of creating a web service for my Angular2 App and I want to incorporate Typescript on the server side as well. After searching online, I have only come across blog posts that provide manual instructions on setting up Typescri ...

Is submitting with JQuery always a hit or miss?

Hey there, I'm currently working on a problem and could use some help. I seem to be having trouble getting inside my function for form submission in JQuery. Despite setting up console.logs, it appears that my code never reaches the first function. Can ...

You must include the formControlName within a parent formGroup directive

Upon creating a model-driven form, an error is encountered: Error: formControlName must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class). ...

Angular: NaNa: Attempting to access a property of an undefined variable

I've encountered these errors although the values are displayed correctly in the browser. I'm unsure about how to resolve this issue. ERROR TypeError: Cannot read property 'length' of undefined ERROR TypeError: Cannot read property &ap ...

"Using the check function in JavaScript to determine if a value

I have a JSON file containing data, and I am looking to create a function that extracts only the values from each object and adds them to a list. Is there a more efficient way to write this code so it can run indefinitely and continue pushing non-object v ...

What is the best way to implement rest parameters in Typescript when making a function call?

I have been working on NestJS and I am facing an issue with retrieving data from the database based on the name property that I pass in a service method. When I pass {"name": "item1"} in Postman, I get data related to item1. However, when I pass {"name":"i ...

Converting Entity Framework nested table queries into JSON format

public class Module { public int id { get; set; } public string moduleName { get; set; } //navigation property public virtual HashSet<Policy> policies { get; set; } } public class Policy { public int id { get; set; } //foreig ...

Creating a Shell Script that will extract key values from a file and transform them into JSON format

My text file is filled with key value pairs structured like this: Var1=Value1 Var2=Value2 Var3=Value3 I managed to turn them into variables using the code below: while read -r line; do declare "$line"; done <inputfile.txt Now I want to transform the ...

Prevent identical objects from being interchangeable in Typescript

I have a situation where I frequently use a StringToString interface: interface StringToString { [key: string]: string; } There are instances when I need to switch the keys and values in my objects. In this scenario, the keys become values and the val ...

Challenges with Loading Picasso Images in Recycler View

Whenever I click on card view items, the images do not display even though the data is loaded correctly using JSON and Picasso. Can anyone help solve this issue with your expertise in the Picasso library? public class SeconActivity extends Activity { Re ...

An error is anticipated when () is added, but surprisingly, I still encounter an error as well. This issue arises in React-Native and Typescript

I am still relatively new to React-Native, but I have been using React-Native, TypeScript, and integrating it with Firebase. An unusual error has occurred, which is visible in the screenshot below. However, when checking in VSC, the error seems to be non-e ...

The error message popped up indicating that JSON_encode in php is not supported

An issue has arisen, showing an error message as json_encode not supported by web server. Below is the snippet of code being affected: <?php require_once('db_login.php'); $con=mysql_connect($db_host,$db_user,$db_password); if(!$con) die ...

Retrieve ag grid from TypeScript file

I am currently utilizing ag-grid-angular in my Angular application to showcase data. I have a button that is located outside the ag grid, and when it is clicked, I need to retrieve all row data from the grid. I am aware that there is an API available for a ...

Converting basic text into JSON using Node.js

Today I am trying to convert a text into JSON data. For example: 1 kokoa#0368's Discord Profile Avatar kokoa#0000 826 2 Azzky 陈东晓#7475's Discord Profile Avatar Azzky 陈东晓#0000 703 3 StarKleey 帅哥#6163's Di ...

Can Pug Templating handle iterating through multiple arrays within a JSON data object?

Exploring Pug for the first time, I have been utilizing JSON files to store the data used in my Pug file. Here is an example of my data structure: { "nav": { "titles": [ "location", "reservations", "accomodations", "ameniti ...

Utilizing Laravel to structure nested JSON responses

I am trying to generate a JSON structure similar to this example in my API controller within Laravel. Below is the snippet of the controller: $data = []; foreach ($products as $p => $product) { // Code logic here } if (count($data) == 1) { $da ...