Using Angular (along with Typescript) to showcase JSON data

I previously shared this query, but unfortunately, I didn't receive many helpful responses

I have a JSON file that holds the following dataset:

[{
    "ID": 1030980,
    "Component": "Glikoza (Gluk)",
    "Result": "16",
    "Date": "20.10.2018"
  },
  {
    "ID": 1030980,
    "Component": "Kreatinin (Creat)",
    "Result": "5",
    "Date": "19.10.2018"
  },
  {
    "ID": 1030989,
    "Component": "Urea (UN)",
    "Result": "1",
    "Date": "19.10.2018"
  },
  ...and so forth
]

UPDATE: I've integrated this code into my patients.component:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
 selector: 'app-patients',
templateUrl: './patients.component.html',
styleUrls: ['./patients.component.css']
})

export class PatientsComponent implements OnInit {
  title = 'Patient Data';

  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    this.http
    .get('./assets/patients.json')
    .subscribe(res => {
      const patients = res['patients'];
      const patient = patients[0];
      for (let i = 0; i < patients.length; i++) {
        let item = patients[i];
        console.log(item['ID'], item['date'], item['component'], item['result']);
      }
    });
  }
}

Now, I aim to extract the 'component' and 'result' based on Patient ID and Date in a tabular format (displaying the results of each component for various dates and IDs). The table should showcase ALL COMPONENTS AND RESULTS for the specific ID and Date, resembling this layout:

table

If you could provide me with some guidance on how to achieve this task, I would greatly appreciate it! Thank you!

Answer №1

I have successfully completed it.

For your reference, here is the stackblitz link :

https://i.sstatic.net/gxqhi.png

Summary of my Approach

To achieve this, I designed a dynamic array of arrays based on the specified date and fields.

public patArray: any[] = [];

this.pat[0].patients.forEach(el => {
      if(this.currentDateString == ""){
        this.currentDateString = el['date'];
        if(!this.skipAssign){
          this.patArray[this.idx] = [];
        }
      }

      if(this.currentDateString == el['date']){
        this.patArray[this.idx].push(el);
      } else {
        this.currentDateString = "";
        this.idx++;
        this.patArray[this.idx] = [];
        this.patArray[this.idx].push(el);
        this.skipAssign = true;
      }
    });

Next, by utilizing a nested ngFor with specific flex properties, I was able to structure the layout effectively:

.flex-ctr{
  display: flex;
  width:100%;
  flex-direction: column;
}

.first{
  display: flex;
  flex-direction: row;
  width:100%;
  height:80px;
  border: 1px solid;
  margin-top: 5px;
}

.tbl{
  display: flex;
  flex-direction: row;
  width:75px;
  height:80px;
}

.table-things{
  display: flex;
  flex-direction: column;
  width:100%;
  font-size: 10px;
  border-right: 1px solid;
  text-align: center;
  align-content: center;
}

.bb{
  border-bottom: 1px solid;
  height:30%;
}

.ss{
  padding-top: 30px;
}

<div class="flex-ctr">
  <div class="first" *ngFor="let data of patArray">
    <div class="tbl" *ngFor="let single of data">
      <div class="table-things">
        <div class="bb">{{single.component}}</div>
        <div class="ss">{{single.result}}</div>
      </div>
    </div>
  </div>
</div>

Answer №2

Close to reaching your goal based on your current progress.

1. Develop a type for patients (Model)

export class Patient {
    constructor(public ID: string,
        //INCLUDE ALL MODEL PROPERTIES
    ) {}
}

2. Connect the model to your Component

  • In your patients.component.ts:

    private patients : Patient[] = [];

Prior to subscribing to the get method on the httpclient, assign your component to a variable to set the model:

var self = this; //Now refers to the PatientsComponent variable
this.http
    .get('./assets/patients.json')
    .subscribe(res => {
      let patients = res['patients'];
      let patient = patients[0];
      self.patients = patients; //SETTING THE MODEL ON THE COMPONENT
      for (let i = 0; i < patients.length; i++) {
        let item = patients[i];
        console.log(item['ID'], item['date'], item['component'], item['result']);
      }
    });

3. Construct your html template with *ngFor

In patients.component.html (modify - bind a list of Components to the component class named components):

<table>
  <thead>
    <th>ID</th> 
    <th>Date</th>
    <th *ngFor="let component of components">{{ component }}</th>
  </thead>
  <tbody>
    <tr *ngFor="let patient of patients">
        <td>{{ patient.ID }}</td>
        <td>{{ patient.Date}}</td>
        <td *ngFor="let component of components"> {{ (patient.Component === component) ? patient.Result : "-" }}</td>
    </tr>
  </tbody>
</table>

4. [UPDATE] Refine the Patient Results

public static FilterFunc(patients : Patient[]) {
    let uniques: Patient[] = [];

    patients.forEach(function (value: Patient, index: number) { 
        if (uniques.some(function (patientCompare: Patient) {
            return (patientCompare.Date === value.Date && patientCompare.ID === value.ID && patientCompare.Component === value.Component);
        })) {
            let updatePatient = uniques.find(function (patientCompare: Patient) {
                return (patientCompare.Date === value.Date && patientCompare.ID === value.ID && patientCompare.Component === value.Component);
            });

            updatePatient.Result += value.Result;
        }
        else { 
            uniques.push(value);
        }
    });

}

In the update, ensure to also link a components : string[]; object to the component. This should include ["crea", "gluk", etc....]

Utilize the filter function to refine your data.

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 is the process of querying both a collection and a subcollection in Firebase using AngularFire?

I have a structure in my firebase database that looks like this: /profiles/{uid}/displayName /email /otherAttribues /roles/{roleName}/someAttribute /someOtherAttribute The reason ...

Error message: `Socket.io-client - Invalid TypeError: Expected a function for socket_io_client_1.default`

I have successfully installed socket.io-client in my Angular 5.2 application, but after trying to connect (which has worked flawlessly in the past), I am encountering a strange error. TypeError: socket_io_client_1.default is not a function at new Auth ...

Minimum width of Angular Material's mat-menu

I am looking to create a compact Material mat-menu using Angular 15. Below is the code I have: <mat-menu #flagMenu="matMenu"> <button mat-menu-item> <img src="assets/flags/en.png" class="flag"/> ...

Guide on exporting a function from a module as a class property

How to export a function as a class property from a module? Even if modifiers such as public are added, when a class property points to a function within a module, it behaves as though it is private. There are multiple ways to define a property (a, b, c ...

What are some strategies for customizing the appearance of child components within a parent component?

I have a scenario where I am using parent and child components. When I use the HTML in another component, I also apply my CSS. For example, in my parent component: HTML <div class="chips"> <p class="tags">Tag 1</p&g ...

Utilizing Flask templates to embed JSON data

I am looking to format JSON data in my app using json.dumps() for a more visually appealing display. Currently, my template structure is as follows: <table> {% for test in list_of_decoded_json %} <tr> <td><pre>{{ test|s ...

What specific data is AR collecting from the XXXJSON webpage?

I have embarked on the challenge of creating an app similar to layar, and I understand that it can be quite complex. As I gather examples for inspiration, I notice that all the information is retrieved from websites like; GeoNames OR Twitter My qu ...

Error encountered: NextJs could not find the specified module, which includes Typescript and SCSS

I am in the process of migrating a Next.js application from .js to .ts and incorporating ScSS. The first error I encounter is during 'npm run dev'. However, when I try 'npm run build', different issues arise that do not seem related to ...

Error occurs when JSON.parse is used

<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script> var data = "{ 'name': 'John' }"; var result = JSON.parse(data); </script> ...

Understanding and decoding complex JSON structures on Windows Phone 8 involving Dictionary Key/Value pairs

Hello, I'm currently diving into the world of Windows Phone 8 development and I could use some assistance with parsing data. Here is an example of the data format I am working with: [ { "detail":{ "single_selection":[ ...

Creating a unique JSON structure with personalized fields

I'm not entirely sure if it's feasible, as I haven't found any specific information on this. Let me try to explain what I want to achieve below. Currently, I am using the requests library to fetch data from an API. Once I have the data, I u ...

Can calculations be performed on JSON fields in SQLAlchemy with Postgres?

I am currently working with sqlalchemy on a postgres database, attempting to perform arithmetic operations in a SELECT query involving two JSON fields representing floats. I have encountered difficulties in getting this functionality to work as intended. ...

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 ...

Consolidate various arrays of objects while eliminating duplicate items based on an optional property

Imagine having multiple arrays like these: const arr1 = [ { "id": "1", "type": "sales" }, { "id": "2", "type": "finance" } ] const arr2 = [ { "type": "s ...

Typescript is experiencing an error due to the use of attr("disabled", false) causing a disruption

Within my ts file, I'm using the code snippet below: $('input[type=hidden]').attr("disabled", false); The code functions as intended, however, an error persists: Argument of type 'false' is not assignable to parameter of typ ...

Expanding on Angular's virtual scroll feature: automatically add new items as you reach the bottom of the

I'm facing a challenge in my Angular application where I want to implement virtual scroll. The items displayed on the list are the outcome of a remote paged search. My goal is to fetch more results (trigger the next page) every time I scroll down to t ...

Strategies for modifying the bound value in Angular with an observable object

I am attempting to convert the offset value for a time object in the URI, which is stored in an observable object. The issue I am encountering is: ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checke ...

Issue encountered with Angular 12 Material table: The data source provided does not match an array, Observable, or DataSource

When my REST API returns the following data: { "id": 1, "userId": 1, "date": "2020-03-02T00:00:02.000Z", "products": [ { "productId": 1, "quantity": 4 }, { "productId": 2, "quantity": 1 }, { "productId": 3, "quantity": 6 } ], "__v": 0 }, I attempt to imple ...

Having trouble converting JSON string into map using Jackson in Java

I am having an issue with this snippet of code where I am attempting to convert a JSON string into a map. String json = "[{'code':':)','img':'<img src=/faccine/sorriso.gif>'}]"; ObjectMapper mapper = new Objec ...

Using Vue.js to process JSON data

My issue lies within this JSON data. I am trying to consume only the first element of the array using Vue.js 2 in order to display it. I was able to achieve this successfully using the console, but not with Vue.js. This line of code in the console works: ...