Guide to extracting the JSON array from a JSON object with Angular

In my angular application, I have made a call to the API and retrieved a JSON object in the console. However, within this JSON object, there are both strings and arrays. My task now is to extract and parse the array from the object in the console.

The JSON object displayed in the console is as follows:

{
"Drone": {
    "Droneid": 1001,
    "latlong": [
        {
            "lat": 12.989839,
            "lon": 80.198822
        },
        {...more coordinates here...}
    ]
}
}

My goal is to extract the "latlong" array from this JSON object.

Dashboard.service.ts

mapping(token){
  let httpOptions = {
    headers: new HttpHeaders({
    'Content-Type': 'application/json',
      'Authorization': 'Token ' + token
    })
  };
  //this.http.get(this.url).subscribe(
    this.http.get(environment.apiurl +'/api/data/json', httpOptions).subscribe(  
    (dronesdt:any)=>{
      localStorage.setItem("dronesdt",JSON.stringify(dronesdt));
      console.log("Drones",JSON.parse(localStorage.getItem("dronesdt")));
 } 
  )
}

How can I specifically access and retrieve the "latlong" array in the console? Any assistance on this matter would be greatly appreciated.

Answer №1

To obtain the latlong field, you can follow these steps:

dashboard.service.ts

mapping(token){
  let httpOptions = {
    headers: new HttpHeaders({
    'Content-Type': 'application/json',
      'Authorization': 'Token ' + token
    })
  };
  // this.http.get(this.url).subscribe(
    this.http.get(environment.apiurl +'/api/data/json', httpOptions).subscribe(  
    (dronesdt:unknown /*Try to avoid any and statically type values as far as possible*/)=>{
      localStorage.setItem("dronesdt",JSON.stringify(dronesdt));
      console.log("Drones", dronesdt.Drone.latlong);
 } 
  // )
}

It is unnecessary to use JSON.parse on the object in the console since you have already retrieved the most recent data within that function.

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

Every time I implement *ngSwitch in a Bootstrap navbar, the visual styling unexpectedly vanishes

<ul class='nav navbar-nav'> <li class='nav-item'> <ul [ngSwitch]='isLoggedIn' class='nav-item'> <li *ngSwitchCase=true> ...

Tips for sending an array of any type to a Lookup function

I'm currently utilizing ngl-lookup from the ngl-lightning library and I'm attempting to pass an array of type any[] instead of String[]. Here's the code snippet I have: <ngl-lookup [lookup]="lookupManagerUsers" [icon]="true" [image]="&a ...

What is the best way to patiently anticipate a response from customer service

My singltone service contains a synchronous method. Upon injecting the service into a component: constructor( private reonMapLibraryService: ReonMapLibraryService ) {} I am unable to access reonMapLibraryService.data; immediately because it is an asy ...

Leveraging the Angular Material 2 table component to showcase data fetched from the backend system according to the user's present location

This question is similar to another one about how to get the current location in Typescript and pass it to a backend, which was answered by libertyernie. However, this time I need help with integrating the current location into an Angular Material 2 table ...

Sorry, but I can't help with that request

Since the latest update of Angular Material, I have encountered some issues with my <md-menu> components. Previously, everything was functioning well with the import of MaterialModule. However, after switching to MatMenuModule or MdMenuModule, an err ...

Encountering challenges with the angular2-infinite-scroll plugin

I encountered 2 errors while using my application: Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:3002/angular2-infinite-scroll angular2-polyfills.js:1243 Error: XHR error (404 Not Found) loading htt ...

Unable to modify the Jest mock function's behavior

The issue I am facing involves the following steps: Setting up mocks in the beforeEach function Attempting to modify certain mock behaviors in specific tests where uniqueness is required Encountering difficulty in changing the values from the in ...

Creating HTML code using an array of objects

My goal is to create HTML tags based on the object response shown below: "view": [{ "type": 'text', "depth": 0, "text": "This is a sample text" }] The objective here is to iterate through each type and add the corresponding HTML tags. &l ...

Display items according to the visible element

Just starting with Angular and could use some guidance In my header component, I have a bootstrap navbar consisting of ul and li elements along with a router outlet. <app-header></app-header> <router-outlet></router-outlet> I&apo ...

Tips for converting text input in a textbox to a Date value

My knowledge of Angular is limited, and we are currently using Angular 10. In our application, there is a textbox where users need to input a date in the format 10202020. This value should then be reformatted as 10/20/2020 and displayed back in the same ...

Transforming a JavaScript component based on classes into a TypeScript component by employing dynamic prop destructuring

My current setup involves a class based component that looks like this class ArInput extends React.Component { render() { const { shadowless, success, error } = this.props; const inputStyles = [ styles.input, !shadowless && s ...

How to use jsZIP in angular to bundle several CSV files into a single zip folder for download

I have a code snippet below that demonstrates how to create data for a CSV file and download the CSV file in a zip folder: generateCSVfiles() { this.studentdata.forEach(function (student) { this.service.getStudentDetails(student.studentId).subsc ...

Exploring the possibilities of customizing themes in Angular Material with Stylus for Angular 5

My project is currently utilizing the "stylus" CSS pre-processor instead of SCSS. I am interested in incorporating Angular Material themes and switching between them. While I can find documentation for SCSS, I am struggling to find resources for stylus. ...

Is there a distinction between Entity[] and array<Entity> in TypeScript?

Everything in the title, for example people: Person[]; people: Array<Person>; What sets them apart? Is there a preferred approach? Note: I couldn't find any guidance on this and I've encountered both in code. ...

How can I restrict a generic type to include the new() method?

Is there a way to create a function similar to the following in TypeScript? createEntity<TEntity>(): TEntity { return new TEntity(); } In C#, we can achieve this using: void TEntity CreateEntity<TEntity>() where TEntity : new() How would ...

Formatting Strings in JavaScript when saving as a .txt file with proper indentation

Utilizing Angular and TypeScript/JavaScript for testing purposes. Each row has been formatted with a newline at the end of the code. formattedStr += car.Name + ' | ' + car.Color + ' | ' + car.Brand + '\r\n' The da ...

The logout feature experiences a malfunction when invoked from the app.component.ts file

I have an authentication Service with a Logout() function implemented as shown below: export class AuthService { isAuthenticated = new BehaviorSubject(false); constructor(private router: Router) { } Logout() { console.log('Logout'); ...

What could be causing the QullJS delta to display in a nonsensical sequence?

The outcome showcased in the delta appears as: {"ops":[{"retain":710},{"insert":" yesterday, and she says—”\n“The clinic?","attributes":{"prediction":"prediction"}},{"del ...

Building a BaseObserver in TypeScript with RxJS

Initially, I created a class called BaseObserver in Swift. In the subscribe method, I pass this class. Now, I am attempting to achieve the same functionality in RxJS using TypeScript. This approach proves useful when you need to execute actions both befor ...

Leverage advanced type deduction in Key Remapping

I'm puzzled by this code snippet: type Foo<T extends string> = [T] extends [infer Y] ? Y : never // works fine type Test_2<T extends Array<string>> = { [P in T[number] as Foo<"foo">]: undefined } // no issues type ...