Tips for accessing nested values post-subscription in Angular with JSON data?

I have implemented a getReports method that utilizes my web API's get method to retrieve JSON formatted responses.

Step1

    getReports() {
            return this._http.get(this.url)
                .map((response: Response) => response.json())
                .catch(this.handleError);  
        }

Step2

In the constructor of my component class, I inject the complete service and subscribe to this.reports within ngOnInit.

constructor(private _reportService: GetReports) {
    }
ngOnInit() {
       this._reportService.getReports().subscribe(reports => this.reports = reports);
}

Upon checking the console, I observe an array containing 127 records. My challenge lies in efficiently traversing this JSON data within the component to display nested values.

Image description available here

For instance, expanding the above array reveals data structured as follows:

0
     Key 1:" abdef",
     Key2 :[1,2,3 ]
     key 3:['test','test2']
1   
    Key 1:" check",
     Key2 :[1,2,3 ]
     key 3:['test3','test2']
 2 
     Key 1:" ghef",
     Key2 :[1,2,3 ]
     key 3:['test3','test2']
 ....
 ....
 ....
 127  
     Key 1:" check",
     Key2 :[1,2,3 ]
     key 3:['test4','test3']

I aim to extract all unique values for Key 1 across the 127 elements as shown above. Similarly, based on Key 1, I plan to identify distinct values under Key 3.

The objective is to retrieve all Key 3 values associated with Key 1 while avoiding duplicate entries.

While exploring resources like access key and value of object using *ngFor, I did not find a solution matching my requirements.

Your guidance on ways to effectively access or interpret nested JSON data in Angular would be highly appreciated.

Answer №1

Retrieve unique keys

const uniqueKeys = reports.map((a) => a.key1).filter((item, pos, arr) => arr.indexOf(item) === pos);

Obtain all key3 values where key1 is equal to "abc"

let results = []
myarr.forEach((item) => {
    if(item.key1 === "abc"){
        results = results.concat(item.key3);
    }
})

results = results.filter((item, pos) => results.indexOf(item) === pos);

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

Steps for specifying the required type of an Object literal in Typescript

Let's analyze a straightforward code snippet interface Foo{ bar:string; idx:number; } const test1:Foo={bar:'name'}; // this is highly recommended as it includes all required fields const test2={bar:'name'} as Foo; // this is ...

Decoding the Gson: Unraveling the Purpose Behind Parsing Intricate Dynamic Data

My current project involves working on an Android application that receives a large amount of dynamic JSON data. Initially, I wrote my custom methods to handle this using the standard org.json packages, but I found it to be messy and plagued with bugs. Af ...

Steps for generating a personalized array using a JSON document

I have been trying to create a customized array from my JSON file, but every time I try to run the code, nothing seems to be coming out. Can someone please help me understand why this is happening? Here is a snippet of my JSON data: [{"Account":null,"Add ...

Utilize Angular-Material to showcase a tooltip when hovering over a form label

I am struggling to display a tooltip on a label. Is there an easy fix for this issue? <mat-form-field> <mat-label matTooltip="Please enter your E-Mail Address"> E-Mail <mat-icon>help_outline</mat-icon> < ...

Sharing assets across different Angular applications is a powerful way to improve code

I am currently developing a series of small applications that will utilize common modules and shared assets. For guidance on how to structure the projects, refer to this answer: The organization of my project folders is as follows: -root --projects ---ap ...

Utilizing JQuery Template to Invoke JavaScript Functions

If I have the following JSON object structure: ITEMS is an array with one element, and FILTER is another array with 3 items in it. Description: "churches with some restrictions" ITEMS: {...} [0]: {...} FILTER: {...} ...

Tips for infuriating TSC with Lookup categories

I'm looking for the Typescript compiler (TSC) to throw errors when I make mistakes in signatures. export class EventEmitter<EventTypes extends { [key: string]: any }> { subscribe<Event extends keyof EventTypes>(type: keyof EventTypes, ...

Establishing the correct data type to be returned from a fetch function in order to align with a specific custom type

My app has two interfaces defined: export interface Job { job_title: string, employer: string, responsibilities: string[] achievements: string[], start_date: string, end_date: string } export interface CreatedJob extends Job { ...

dynamically open ngx-bootstrap accordion panels

I implemented the ngx-bootstrap accordion feature to display a list of blog posts. Below is the template structure: <accordion id="blog-list"> <accordion-group *ngFor="let post of posts; let first = first;" [isOpen]="first" id="post-{{post.i ...

Removing the initial and final curly braces from a JSON within WSO2 ESB involves utilizing specific methods or functions to manipulate

Json { { "id": "", "name": "", "status": "" }, { "id": "", "name": "", "status": "" }, { "id": "", "name": "", "status": "" } } The task at hand involves eli ...

Unlocking the Secrets of Passing ID Parameters Between Pages and Fetching Data from External APIs in Ionic 4

Before I get into it, apologies for the basic question, but I'm struggling to figure this out. Here's my issue: I have a list of categories that are being fetched from a nodeJS api. My goal is to fetch the subcategories based on the id from the d ...

The proper order for logging in is to first validate the login credentials before attempting

I created a custom validation class to verify if a user is logged in before allowing them access to a specific page. However, after implementing this validation, my program no longer routes me to the intended component. Validation.ts export class UserVal ...

Google Chrome does not support inlined sources when it comes to source maps

Greetings to all who venture across the vast expanse of the internet! I am currently delving into the realm of typescript-code and transcending it into javascript. With the utilization of both --inlineSourceMap and --inlineSources flags, I have observed t ...

What is the process for configuring NextJS to recognize and handle multiple dynamic routes?

Utilizing NextJS for dynamic page creation, I have a file called [video].tsx This file generates dynamic pages with the following code: const Video = (props) => { const router = useRouter() const { video } = router.query const videoData = GeneralVi ...

Encountering a promise error when using TypeScript and React Lazy

I've been working with React and TypeScript, incorporating a higher order component to verify user authentication. However, after implementing the hoc, I encountered an error in my routes: /home/nidhin/Documents/Nidhinbackup/F/iot-remsys-demotwo/rem ...

Passing an event from onSubmit in React without using lambdas

Within our current project, the tslint rule jsx-no-lambda is in place. When attempting to capture event from onSubmit, this is how I typically write my code: public handleLogin = (event: React.FormEvent<HTMLFormElement>) => { event.preventDe ...

Is it possible to implement a redirect in Angular's Resolve Navigation Guard when an error is encountered from a resolved promise?

I have integrated Angularfire into my Angular project and am utilizing the authentication feature. Everything is functioning properly, however, my Resolve Navigation Guard is preventing the activation of the component in case of an error during the resolve ...

Move the creation of the HTML string to an HTML template file within ngx bootstrap popover

I have incorporated ngx bootstrap in my project through this link To display dynamic HTML content in the popover body, I am using a combination of ngx-bootstrap directives and Angular template syntax as shown below: <span *ngFor="let item of items;"&g ...

Tips for showing JSON information in Nativescript

How can I display all values in a page using the provided JSON data? res { "StatusCode": 0, "StatusMessage": "OK", "StatusDescription": [ { "sensors": [ { "serial": "sensor1", "id": "1" }, ...

Avoid inserting line breaks when utilizing ngFor

I am using ngFor to iterate through a list of images like this: <div class="image-holder" *ngFor="let image of datasource"> <img src="{{image.url}}" height="150" /> </div> Below is the corresponding CSS code: .image-holder { di ...