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

Setting up a Form submit button in Angular/TypeScript that waits for a service call to finish before submission

I have been working on setting up a form submission process where a field within the form is connected to its own service in the application. My goal is to have the submit button trigger the service call for that specific field, wait for it to complete suc ...

Leverage the useParams data to serve as a state object key in the useSelector function using TypeScript

Looking to access state data using a key obtained from useParams? Here's an example: export const MainPageSection = (props:MainPageSectionPropsType) => { const params = useParams(); const currentSection = params.section const excursions ...

Prevent updating components when modifying state variables

Introduction I've developed a React component that consists of two nested components. One is a chart (created with react-charts) and the other is a basic input field. Initially, I have set the input field to be hidden, but it becomes visible when the ...

The checkbox component is currently not displaying on the ngx-datatable

The following HTML code snippet demonstrates a sample layout. The operations are functioning correctly, however, the checkbox is not visible. <ngx-datatable style="width: 90%" class="material" [rows]="rows" ...

Protractor Browser Instance Failure

We have encountered an issue with our UI suite failing in Chrome during the login process. Initially, we thought it might be due to upgrading to Chrome 79, as the problems arose simultaneously. Interestingly, the login functionality still works smoothly in ...

An issue occurred with npm resulting in exit code 2. The error is as follows: Command was unsuccessful: node_modules/.bin/vsce package --no

Here is the specific error displayed in cmd: TS1323: Dynamic imports are only supported when the '--module' flag is set to 'es2020', 'esnext', 'commonjs', 'amd', 'system', or 'umd'. E ...

Leveraging external libraries within Angular2 and SystemJS

I am relatively new to the world of TypeScript and I am currently attempting to integrate a third-party library into my Angular 2 application. Specifically, I am trying to utilize https://www.npmjs.com/package/marked in order to parse markdown within my ap ...

GitHub Actions causing build failure in Angular project exclusively

I've encountered an issue where the GitHub Action workflow fails to compile an Angular project, even though it works fine on my local machine and that of my colleagues. It's worth noting that I'm using npm ci instead of npm install. The err ...

Combining Angular subscriptions to fetch multiple data streams

I am looking to retrieve the most recent subscription from a group of subscriptions. Whenever the value of my FormControl changes, I want to capture only the latest value after the user has finished typing. Below is the code snippet I am using - let cont ...

Using TypeScript with knockout for custom binding efforts

I am in the process of developing a TypeScript class that will handle all bindings using Knockout's mechanisms. Although I have made progress with the initial steps, I have encountered a roadblock. While I can successfully bind data to my HTML element ...

The identity of the property cannot be located within undefined

<ion-content padding> <ion-list> <ion-item> <ion-label fixed>Username</ion-label> <ion-input type="text" value="" (ngModel)]="userData.username"></ion-input> </ion-item& ...

Utilize Lambda Layer to seamlessly share interfaces/types across Lambda Functions

I have a lambda layer file that contains an enum definition (which will be used in various lambda functions) as shown below: exports enum EventTypes { Create, Delete, Update, } Initially, everything was working well as I tested ...

Sharing interfaces and classes between frontend (Angular) and backend development in TypeScript

In my current project, I have a monorepo consisting of a Frontend (Angular) and a Backend (built with NestJS, which is based on NodeJS). I am looking to implement custom interfaces and classes for both the frontend and backend. For example, creating DTOs s ...

What is the equivalent of specifying globalDevDependencies for npm @types packages in typings?

I am looking to update a project using tsc@2 and remove typings from my toolchain. Updating common dependencies is easy as they are listed in my typings.json file: "dependencies": { "bluebird": "registry:npm/bluebird#3.3.4+20160515010139", "lodash": ...

How can you utilize Angular 2's http.post method to interact with a web API2 controller method from a component?

ClassComponent.ts fetchTableHeaders(Id: any) { let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); let body = JSON.stringify(Id); var request = this. ...

Create an entity with a field that holds a value type based on the value of another key field

Essentially, I am looking to create a customized "Pair" data type For example: type Pair<T extends Record<string, string | number>, K extends keyof T> = { field: K, value: T[K] } So, if we have: type Rabbit = { name: string, a ...

The call stack size has reached its maximum limit due to running 2 Collection.find commands

I've encountered a Maximum call stack size exceeded exception in my Chrome console while working with Angular2 and Meteor. This issue started after I added the following code to my client side: var userChannelsId = UserChannels.find({idUser: Meteor.u ...

What could be causing the issue: Unable to locate or read the file: ./styles-variables?

I'm currently following a tutorial on how to create responsive layouts with Bootstrap 4 and Angular 6. You can find the tutorial here. I've reached a point where I need to import styles-variables.scss in my styles file, but I keep encountering t ...

There was an issue with loading resources in ASP.NET MVC with Angular 2 as the server responded with a 404 (Not Found) error

Encountering some unexpected behavior with typescript imports in ASP.Net MVC using Angular 2. The issue arises when the code errors at runtime stating it cannot locate the ng2-highcharts package from the root directory, rather than within node_modules. Al ...

Adding elements to a page while it is running can be achieved using a variety

Working on a college project, I am developing a demo web-app in Angular. The goal is to implement a feature where clicking a button adds a new node to the DOM tree. In JavaScript, a simple solution would be: document.getElementById('ticket-container& ...