Presenting a hierarchical JSON structure from a RESTful API in tabular form

I'm struggling to showcase nested JSON data retrieved from my backend server in a table format.

Below is the JSON structure:

{
  "id": 1,
  "personalData": {
    "firstName": "Bob",
    "lastName": "Bobby",
    "personalIdNumber": 852963
  },
  "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="35575a57574c575a5775575a571b565a571b565a">[email protected]</a>",
  "correspondenceAddress": {
    "addressLine1": "Sesame Street",
    "addressLine2": "1",
    "addressLine3": "2",
    "city": "Disney",
    "province": "Cartoons",
    "zipCode": "01-234"
  },
  "companyId": 265385,
  "active": true
}

I aim to exhibit the firstName, lastName, email, companyId, and active fields in a tabular form.

Here is the method used to fetch data:

getData(): void {
    this.service.getAll()
      .subscribe((data) => {
          this.dataList = data;
        },
        error => console.log(error)
      );
  }

And here is the HTML code for the table:

<div class="table-responsive">
      <table class="table" *ngIf="dataList && dataList">
        <thead>
        <tr>
          <th>First name</th>
          <th>Last name</th>
          <th>E-Mail</th>
          <th>Company ID</th>
          <th>Active?</th>
          <th></th>
        </tr>
        </thead>
        <tbody>
        <tr *ngFor="let data of dataList">
          <td>{{data.firstName}}</td>
          <td>{{data.lastName}}</td>
          <td>{{data.email}}</td>
          <td>{{data.companyId}}</td>
          <td>{{data.active ? "True" : "False"}}</td>
          <td>
            <button class="btn btn-primary" (click)="openDetails()">Details</button>
          </td>
        </tr>
        </tbody>
      </table>
    </div>

The PersonalData and CorrespondenceAddress sections will always be singular. How can I efficiently interpret them and present in the table?

Answer №1

Structured Data Response

If your data is structured like the example below in a JSON format, you can create arrays to store and display it efficiently:

{
  "id": 1,
  "personalData": {
    "firstName": "Alice",
    "lastName": "Anderson",
    "personalIdNumber": 123456
  },
  "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1234567890abcdef">[email protected]</a>",
  "address": {
    "streetAddress": "Main Street",
    "city": "Cityville",
    "state": "Statewood",
    "zipCode": "12345"
  },
  "companyId": 987654,
  "active": true
}

To handle this data effectively, create arrays in your code:

personalData: any[] = [];
address: any[] = [];
dataList: any[] = [];

You can then write a method to extract and organize the data as needed:

getDetails(){
   this.personalData = this.array.personalData;
   this.address =  this.array.address;

   console.log('Personal Data => ', this.personalData);
   console.log('Address => ', this.address);

   this.dataList.push({personalData: this.personalData, address: 
   this.address, array: this.array })

   console.log('Data List =>', this.dataList);
}

Make sure to call the getDetails() method within the ngOnInit() method for automatic execution when the class initializes.

In your HTML, you can display the structured data using Angular directives:

<div class="table-responsive">
      <table class="table" border="1">
        <thead>
        <tr>
          <th>First Name</th>
          <th>Last Name</th>
          <th>E-Mail</th>
          <th>Company ID</th>
          <th>Active?</th>
          <th>Address</th>
        </tr>
        </thead>
        <tbody>
        <tr *ngFor="let data of dataList">
          <td>{{data.personalData.firstName}}</td>
          <td>{{data.personalData.lastName}}</td>
          <td>{{data.array.email}}</td>
          <td>{{data.array.companyId}}</td>
          <td>{{data.array.companyId}}</td>
          <td>{{data.address.streetAddress + data.address.city + data.address.state}}</td>
          <td>
            <button class="btn btn-primary" (click)="openDetails()">Details</button>
          </td>
        </tr>
        </tbody>
      </table>
    </div>

Here is a sample StackBlitz with structured data: Check it out here


Organized Array Data

If your response is in an organized array format like the one below, you can work with it similarly:

dataList = [
    {
      id: 1,
      personalData: {
        firstName: "Charlie",
        lastName: "Chaplin",
        personalIdNumber: 654321
      },
      email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="badcdefcdabedfbacadebdcdbccdfcacacd">[email protected]</a>",
      address: {
        streetAddress: "Broadway",
        city: "Hollywood",
        state: "Starland",
        zipCode: "54321"
      },
      companyId: 123456,
      active: false
    }
  ]

In your HTML template, you can iterate through the array to display the content:

<tbody>
        <tr *ngFor="let data of dataList">
            <td>{{data?.personalData?.firstName}}</td>
            <td>{{data?.personalData?.lastName}}</td>
            <td>{{data?.email}}</td>
            <td>{{data?.companyId}}</td>
            <td>{{data?.address?.streetAddress +
             data?.address?.city +
              data?.address?.state}}</td>
            <td>{{data?.active ? "Yes" : "No"}}</td>
            <td>
                <button class="btn btn-primary" (click)="openDetails()">Details</button>
            </td>
        </tr>
    </tbody>

Explore this StackBlitz example showcasing organized array data: Take a look here

Answer №2

It is anticipated that you will have an array structured as follows

dataList = [
    {
        id: 1,
        personalData: {
            firstName: "Bob",
            lastName: "Bobby",
            personalIdNumber: 852963
        },
        email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="35575a57574c575a5775575a571b565a58">[email protected]</a>",
        correspondenceAddress: {
            addressLine1: "Sesame Street",
            addressLine2: "1",
            addressLine3: "2",
            city: "Disney",
            province: "Cartoons",
            zipCode: "01-234"
        },
        companyId: 265385,
        active: true
    },
    {
        id: 2,
        personalData: {
            firstName: "Sam",
            lastName: "V",
            personalIdNumber: 852963
        },
        email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="196a78746f597e74787075377a7674">[email protected]</a>",
        correspondenceAddress: {
            addressLine1: "Sesame Street",
            addressLine2: "1",
            addressLine3: "2",
            city: "Disney",
            province: "Cartoons",
            zipCode: "01-234"
        },
        companyId: 265385,
        active: true
    }
]

In order to showcase this data in a table format:

<div class="table-responsive">
<table class="table">
    <thead>
        <tr>
            <th>First name</th>
            <th>Last name</th>
            <th>E-Mail</th>
            <th>Company ID</th>
            <th>Active?</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let data of dataList">
            <td>{{data?.personalData?.firstName}}</td>
            <td>{{data?.personalData?.lastName}}</td>
            <td>{{data?.email}}</td>
            <td>{{data?.companyId}}</td>
            <td>{{data?.active ? "True" : "False"}}</td>
            <td>
                <button class="btn btn-primary" (click)="openDetails()">Details</button>
            </td>
        </tr>
    </tbody>
</table>

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

Struggling with fetching the email value in .ts file from ngForm in Angular?

I'm trying to retrieve the form value in my .ts file, but I am only getting the password value and not the email. Here is the code snippet: <div class="wrapper"> <form autocomplete="off" class="form-signin" method="post" (ngSubmit)="lo ...

What are the steps to create an Angular 8 application with a node backend and deploy it on Firebase?

My goal is to create a web scraper using node and then transfer that data to my angular front end. I am interested in hosting this Progressive Web App on firebase because of its user-friendly interface and cost-effectiveness. This will be my first attempt ...

Guide on importing JavaScript into TypeScript without using noImplicityAny and while not allowing Js

In my development setup, I am utilizing Webpack along with @babel/typescript to compile a project that consists of a mix of TypeScript and JavaScript. To ensure better typing and take advantage of the benefits it offers, I have enabled the --noImplicitAny ...

When the page reloads, the checkboxes are already checked but do not contain any initial values

The current configuration functions properly when I toggle checkboxes and submit to the server. However, upon reloading the page or entering edit mode, everything loads correctly and the checkboxes are checked with the corresponding entries displayed like ...

Function arity-based type guard

Consider a scenario where there is a function with multiple optional parameters. Why does the function's arity not have a type guard based on the arguments keyword and what are some solutions that do not require altering the implementation or resorti ...

What is the reason for the extended delay in nodejs before it exits?

Attempting to create a Creation Operator to obtain an observable from a wsprovider on polkadot.js and access polkadot events. Here is the code snippet: import {from, fromEvent, of,Observable} from 'rxjs'; import {tap,mergeMap} from "rxjs/op ...

Searching for a particular entry in Firebase

I have a Firebase database set up like this https://i.sstatic.net/SnW85.png When I need to locate a specific box, I use Angular url = 'https://box-xxxyyy.firebaseio.com'; getBox( box: string) { return this.http.get<any>(`${ this.u ...

The dropdown-menu is positioned in a different location than its relative position

Utilizing the bootstrap dropdown feature in the navigation bar with a menu (represented by three dots) icon https://i.sstatic.net/vR13Z.png However, the issue arises on mobile devices. When I open the navigation bar and click on the menu button, the dropd ...

Learning how to implement GraphQL in Angular without relying on the Apollo client library poses an exciting challenge for

Exploring ways to incorporate GraphQL into my Angular app without relying on the Apollo client. Any suggestions on how this can be achieved? Although I've used the Apollo client for connecting to a GraphQL API in the past, I'm curious about alte ...

I recently used the ng new ang-routing command to generate a fresh Angular project in my directory, but encountered an error while doing so

npm ERR! syscall read npm ERR! errno ECONNRESET npm ERR! network Invalid response body while trying to fetch https://registry.npmjs.org/@angular-devkit%2fbuild-angular: read ECONNRESET npm ERR! network This issue is likely caused by connectivity problems. ...

Tips on showcasing multiple values using Angular 4?

Using angular 4 and spring boot, I retrieve a list of records from spring boot to angular 4 but only display a single object in the form. How can I list multiple values in the search box? component.ts: Within this component, all the values are retrieved b ...

npm ERROR: The start script for [email protected] has encountered a failure with the commands 'tsc && concurrently "tsc -w" "lite-server"'

I followed a tutorial to make changes to the app/main.ts file and now I am encountering errors when I try to run "npm start": Here is the project file with the commit message error: https://github.com/monajalal/angular2_projects import {bootstrap} fro ...

Issue with mediaelement in Angular 8: video playback does not display after 2 seconds

I'm encountering an issue with MediaElement js when trying to play videos in .m3u8 format within a slider containing multiple videos. Whenever I click on the play button for any video, only a 2-second clip is shown before the video disappears. Any as ...

Exploring the Power of NgRx in Angular 8 with the mat-tree Component

Recently, I started developing an app using Angular 8 and integrating Angular Material into it, even though I am still a beginner with the framework. However, I enjoy taking on challenges! One of the most intriguing features of my app is the ability to di ...

Tips for managing the error message "The key 'myOptionalKey' is optional in the 'myObject' type but necessary in the '{...}' type"

Issue I'm currently working on making a sortable table using a sample table component from Material-UI. I encountered an error when I included an optional key in the Data object. It seems that the type definition in the getComparator function does no ...

unable to select date on mat-calendar

I'm trying to add special dates to a mat-calendar by highlighting them. Here's the code I have so far: app.component.ts: datesToHighlight = ["2019-06-22T18:30:00.000Z", "2019-06-06T18:30:00.000Z", "2019-06-24T18:30:00.000 ...

React development: How to define functional components with props as an array but have them recognized as an object

While trying to render <MyComponent {...docs} />, I encountered the following error: TypeError: docs.map is not a function Here's how I am rendering <MyComponent /> from a parent component based on a class: import * as React from &apo ...

The 'autoComplete' property cannot be found within the 'IntrinsicAttributes & InputProps' type

I'm currently utilizing Typescript and React, but encountering the following error: Property 'autoComplete' is not found on type 'IntrinsicAttributes & InputProps'. This is how I am using the component: <Input ...

Angular 13 vulnerability alert triggered by loader-utils bug

After updating to Angular version 13, I discovered 5 critical vulnerabilities: loader-utils <=1.4.1 || 2.0.0 - 2.0.3 Severity: critical Prototype pollution in webpack loader-utils - https://github.com/advisories/GHSA-76p3-8jx3-jpfq Prototype pollution ...

Expanding ngFor in Angular 2

Is it possible to pass two arguments with ngFor? Here is an example that I would like to achieve: <mat-card *ngFor="let room of arr; let floor of floorArr"> <mat-card-content> <h3>Room Number: {{room}}</h3> <p>Floor ...