How do you navigate through nested JSON data with Angular's httpModule to access specific nodes?

How can I access nested nodes in JSON data? I've managed to retrieve the parent level, but when trying to access nested/sub-records, I'm getting [object Object],[object Object],[object Object]. Any suggestions on how to display another ul-li for assigned_to with multiple records?

db.json

"users": [
    {
      "id": 1,
      "first_name": "Male",
      "last_name": "Record",
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="600d010c054e1205030f120420070d01090c4e030f0d">[email protected]</a>",
      "gender": "Male",
      "dob": "01-01-1987",
      "impact": "Not Applicable",
      "score": "Updated",
      "checked": false,
      "assigned_to": [
        {
          "co_score": 54,
          "dl": "CAT1",
          "sub_impact": "Applicable",
          "comments": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."
        },
        {
          "co_score": 20,
          "dl": "CAT2",
          "sub_impact": "Not Applicable",
          "comments": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."
        },
        {
          "co_score":99,
          "dl": "CAT1",
          "sub_impact": "Applicable",
          "comments": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."
        }

      ]
    },
    {
      "id": 2,
      "first_name": "Female",
      "last_name": "Record",
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e781828a868b82c99582848895883a78898c8288c08c8088">[email protected]</a>",
      "gender": "Female",
      "dob": "31-12-1987",
      "impact": "Not Applicable",
      "checked": false,
      "score": "Updated"
    }
 ]
}

app.component.html

<table class="table table-sm table-responsive">
      <thead>
        <tr>
          <th>
            <input type="checkbox" name="allNonTrades" (change)="selectAllClicked($event)">
          </th>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Email</th>
          <th>Gender</th>
          <th>DOB</th>
          <th>Impact</th>
          <th>Score</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr class="record-row" (click)="viewUser(user)" *ngFor="let user of allUser | tableFilter: form.value | paginate: { id: 'listing_pagination', itemsPerPage: 10, currentPage: page, totalItems: totalRecords }">
          <td><input *ngIf="!isEdit"  name="nontrades" [checked]="user.selected" (change)="changeTradesByCategory($event)" [(ngModel)]="user.checked" type="checkbox" (change)="checkboxClicked()"></td>
          <td>{{user.first_name}}</td>
          <td>{{user.last_name}}</td>
          <td>{{user.email}}</td>
          <td>{{user.gender}}</td>
          <td>{{user.dob}}</td>
          <td>{{user.impact}}</td>
          <td>
            <div [ngClass]="getClass(user)">{{user.score}}</div>
            <div>
              {{user.assigned_to}}
            </div>
          </td>
          <td>
            <button *ngIf="!isEdit" class="btn btn-primary btn-sm" (click)="editUser(user)">Edit</button>
            <button class="btn btn-primary btn-sm btn-sm ml-2" (click)="deleteUser(user)">Delete</button>
          </td>
        </tr>
      </tbody>
    </table>

app.component.ts

getLatestUser() {
    this.commonService.getAllUser().subscribe((response) => {
      this.allUser = response;
      this.totalRecords = this.allUser.length;
      this.getApplicableCounts();
      this.allUser.forEach((row: any) => row.checked = false);      
    });
  }
constructor(private commonService: CommonService) {}
  ngOnInit() {
    this.getLatestUser();    
  }

service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class CommonService {

  constructor(private http:HttpClient) { }

  getAllUser() {
    return this.http.get("http://localhost:3000/users");
  }
  
}

Output: https://i.sstatic.net/RcfJS.png

Answer №1

Instead of the usual method, consider this alternative:

<div>
  {{user.assigned_to}}
</div>

Rather than the above code snippet, you can use another ngFor loop to display customized content:

<ul>
  <li *ngFor="let assignee of user.assigned_to">{{assignee.dl}} - {{assignee.co_score}}</li>
</ul>

Answer №2

Try using {{user.score | json}} and observe the outcome. Ensure you have a way to troubleshoot any errors that may occur.

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

What are the constraints to consider when working with JSON in a practical setting

I find myself at a pivotal point in my application design process. The project at hand is an ASP.NET web application that utilizes REST to request information on various products. Some of these products have different ProductIDs based on their attributes a ...

Utilizing GSON to serialize and deserialize a collection proxy

I have a unique class implementing a custom List<T> and encapsulating an ArrayList<T> that it works with by delegation. The structure is similar to the following: class ListWrapper<T> implements List<T> { private String id ...

d3 file is functional on Firefox but experiencing issues on Chrome

Currently, I'm part of a team project and have run into an issue where the d3 map is rendering correctly on everyone else's computer except mine. Below is a snippet of my map code: var g = svg.append("g"); // The function(error, us) callback wo ...

What is the best way to transform an array into valid JSON format?

Looking to reformat my array in JSON form product[0]['product_id'] product[0]['name'] .... product[1]['product_id'] product[1]['name'] ... After using JSON.stringify(), the output is as follows: {"0":{"product_id" ...

Adjust the size of the image obtained from the JSON data

I am currently working on parsing JSON data which includes an image field that I want to adjust to a specific size. Despite my many attempts at tweaking the code, I seem to have lost track of why it is not functioning as desired. JSON var items=[]; ...

Guidelines for Positioning Text in SVG Using D3.js

I am struggling with aligning the text "Gross Domestic Product" and "Units: Billions of Dollars Seasonal Adjustment: Seasonally Adjusted, Annual Rate Notes: A Guide to the National Income and Product Accounts of the United States (NIPA)" in my visual data ...

The issue of unresolved import modules in Angular 2 within Visual Studio 2015

After setting up a blank web project, I used Angular-cli to add the necessary files. You can find more information on how to use Angular-cli for faster Angular 2 projects in this link. I am able to run the website smoothly using ng build/serve commands. Ho ...

Evaluating the functionality of a pipeline that relies on various services

There is a custom pipe in my Angular application that sanitizes HTML, defined as follows: import { Pipe, PipeTransform } from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; @Pipe({ name: 'sanitiseH ...

Tips for using a container as projected content in Angular

Can a container or wrapper markup be passed into a component as projected content? See below for an example: This is how I would like to implement it <my-component> <div class="wrapper"> <ng-content></ng-content> ...

Filtering in Angular Material Table can be customized using the filter

Is there a way to filter data based on a specific object key? For example, filtering a set of skills to only show those at level 2. I have searched through various resources like the GitHub example and this Stack Overflow question, but I couldn't fin ...

Serializing JSON data in C# involves converting objects or data structures

I need to retrieve 2 distinct columns values from the Country Master table in JSON format using C#. However, I am encountering an error message that says "Object reference not set to an instance of an object." Below is my code snippet: using System; usi ...

Update not reflecting in Angular Reactive Form custom component value

I've developed a custom input component that extends the primeng spinner component. However, I'm facing an issue with Angular Reactive Form where the model value of my component is not being updated. To make it easier to debug, I've created ...

Guide to using Enums in *ngIf statements in Angular 8

I have defined an enum type in my TypeScript file, and I want to use it as a condition in my HTML code. However, when trying to access the "values" of the enum, they appear to be undefined even though I have declared them and inherited from the exported en ...

Modify the value of a property in an array of objects using Angular within an HTML

I am working with an object structure like this: class FileData { file: File; description: string; } Within my components.ts file, I have an array of FileData objects of varying lengths. The corresponding component.html code looks like this: < ...

Is it possible for me to tap into the component creation process within the Angular Router?

Inspiration struck me when I realized the potential of adding a directive to the component designed for this particular route. It would elevate the functionality by letting me convey crucial information in a more declarative manner. Despite learning that ...

Combine all the elements in a JSON List into a single element using Java

Within my database, I have a collection of JSON entries structured like this: Entry 1: { "detail": { "10": { "female": { "visited_person_count": 1, "visited_stay_time_sum": 10 ...

Transforming unprocessed text into a regular string in the Rust programming language

I've been working on decoding raw bytes using base64::decode and I keep getting output that looks like {"foo":1,"bar":"first"}. However, serde_json requires the format to be { "foo":1, "bar":"first" } So, I am tasked with converting let raw = r#"{"fo ...

Guide to organizing an object containing a named list of objects by a specific field in Typescript

I've been working with data in JavaScript, and so far I've been able to do everything I needed on my own. However, I've hit a roadblock. Explaining the structure of my data is tricky, so let's create a schema for it. Here's what I ...

Could you suggest a method to appease the value residing within this location?

Services.ts We are looking to extract the data from this API. How can we log this information? findAllCourses() { return this.http.get(`/api/all-courses`) .pipe( map(res => res["courses"]) ); } ...

The icons within the <i> tag are failing to appear on my Ionic webpage

Trying to incorporate the tag icon in the HTML, but encountering issues with displaying the icon. Here is the code snippet I am using to display the icon, but unfortunately it's not appearing: <i class="fas fa-plus"></i> Intere ...