What is the best way to display this group in a JSON format within a PrimeNG table?

{
    "TN 47 AS 7269": [
        {
            "date": "2020-06-11",
            "paramValue": "Fuel consumed",
            "VehicleNumber": "TN 47 AS 7269",
            "value": "100"
        },
        {
            "date": "2020-06-11",
            "paramValue": "Engine Oil",
            "VehicleNumber": "TN 47 AS 7269",
            "value": "200"
        },
        {
           "date": "2020-06-11",
            "paramValue": "Coolent Oil",
            "VehicleNumber": "TN 47 AS 7269",
            "value": "300" 
        }  
    ],
    "AN 32 GB 3572": [
        {
            "date": "2020-06-11",
            "paramValue": "Fuel consumed",
            "VehicleNumber": "AN 32 GB 3572",
            "value": "300"
        },
        {
            "date": "2020-06-11",
            "paramValue": "Engine Oil",
            "VehicleNumber": "AN 32 GB 3572",
            "value": "400"
        },
        {
            "date": "2020-06-11",
            "paramValue": "Coolant Oil",
            "VehicleNumber": "AN 32 GB 3572",
            "value": "600"
        }
    ]
}

Looking for help to bind vehicle registration numbers and values in corresponding columns using PrimeNG. The JSON data is grouped by the vehicle registration number, which makes it challenging. Any suggestions on how to work with this format would be appreciated.

HTML:

<p-table #tt [columns]="cols" [value]="vehicles" [rows]="10" [paginator]="true" [showCurrentPageReport]="true" 
currentPageReportTemplate="Showing {first} to {last} of {totalRecords} entries" [rowsPerPageOptions]="[10,25,50]">

// For Column Header:
<ng-template pTemplate="header" let-columns>
 <tr><th style="width: 10%;" class="text-center">S.No</th>
  <th *ngFor="let col of columns" [style.width]="col.width" [pSortableColumn]="col.field" class="text-center">
        {{col.header}}
 <p-sortIcon *ngIf="col.field" [field]="col.field" ariaLabel="Activate to sort"
    ariaLabelDesc="Activate to sort in descending order"
    ariaLabelAsc="Activate to sort in ascending order"></p-sortIcon>
    </th>
   </tr>
</ng-template>

// For Table Value:
<ng-template pTemplate="body" let-rowData let-columns="columns" let-rowIndex="rowIndex">
  <tr>
     <td class="text-center">{{rowIndex+1}}</td>
     <td *ngFor="let col of columns" class="text-center">
     <div *ngIf="col.field">
     <span [ngSwitch]="col.field">
     <span *ngSwitchDefault>{{rowData|field:col}}</span>
     </span>
     </div>
     </td>
   </tr>
</ng-template>
</p-table>

TS:

cols = [
    { field: 'VehicleNumber', header: 'Vehicle Registration Number' },
    { field: 'value', header: 'Fuel Consumed' },
    { field: 'value', header: 'Engine Oil' },
    { field: 'value', header: 'Coolent Oil' },
    
  ];

SampleTable Image: https://i.sstatic.net/dWwFr.png

Answer №1

To properly format your JSON data from the backend, you should consider structuring it like this example:

this.vehicleData = Object.keys(data).map(key => {
  return {
    vehicleNumber: key,
    fuelConsumed: data[key][0].value,
    engineOil: data[key][1].value,
    coolantOil: data[key][2].value
  };
});

The way you've defined your cols variable seems unconventional. It might be better to define it as follows:

this.columns = [
  { field: "vehicleNumber", header: "Vehicle Registration Number" },
  { field: "fuelConsumed", header: "Fuel Consumed" },
  { field: "engineOil", header: "Engine Oil" },
  { field: "coolantOil", header: "Coolant Oil" }
];

For a working example, check out this StackBlitz link.

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

Is there a way to prevent an undefined legend from being automatically created in an ng 2 chart during the loading process?

While working with the ng-2 chart, I noticed that an undefined legend is automatically generated in the stacked bar chart with a color that I did not specify. I am using a specific set of colors defined in an array. Is there a way to remove only the undefi ...

Breaking news in the world of programming! The @types/tabulator-tables import is causing a

When you install the following packages: npm install tabulator-tables npm install @types/tabulator-tables And then import them like this: import Tabulator from 'tabulator-tables'; You may encounter an error: Module Usage (Error node_modules @ty ...

Storing Angular files with JBoss caching

My angular 13 application is deployed in a war file on jboss and tomcat application server. Unfortunately, users are facing an issue where they have to forcefully refresh cached files with ctrl+f5 in their browser every time changes are deployed in order t ...

Issue with the physical back button on Android devices

Whenever I press the physical Android Button I encounter the following error: While executing, an unhandled exception java.lang.IndexOutOfBoundsException: setSpan (2..2) goes beyond length 0 Here is my app.routing.ts import { LoginComponent } from " ...

Tips for creating a script that waits for a specific amount of time before moving on to the next execution block in Protractor

Need to automate a test case that involves filling out a form with 5 date pickers and 30 fields. Once the form is filled, a jar needs to be invoked to retrieve the data from the DB and process it independently. Note: The jar does not send any value back t ...

Obtain the Vue Class Component Decorator's method within a Watcher

My question is similar to the ones raised in this and this GitHub issue, but unfortunately they were closed without a solution. I am working with Vue and TypeScript using Vue Class Components. I need to access a method of my Vue class from inside a watche ...

TS2345: The argument provided, which is of type 'Event', cannot be assigned to the parameter expected, which is of type 'HtmlInputEvent'

I am facing an issue while trying to upload a file, and I could use some assistance in resolving it. Angular-----Error: src/app/admin/producto/create-producto-dialog.html:38:47 - error TS2345: Argument of type 'Event' is not assignable to parame ...

The code is looking for an assignment or function call, but found an expression instead: no-unused-expressions

Why am I encountering an ESLint error when using Ternary with 2 statements here? ESLint Error: no-unused-expressions res?.isSuccessful ? (this.toastService.showToast(res.message, 'success'), this.queueDataService.addMember(attendee)) : ...

Is there a way to determine which response corresponds to each request when hitting the same endpoint multiple times?

When making multiple requests to an API endpoint, how can I differentiate the response for each specific request? For example, if a user clicks the upload button three times, how can I track each request individually? ...

Setting model value in Angular 2 and 4 from loop index

Is it possible to assign a model value from the current loop index? I've tried, but it doesn't seem to be working. Any suggestions on how to achieve this? Check out this link for my code <p *ngFor="let person of peoples; let i = index;"& ...

The button click function is failing to trigger in Angular

Within my .html file, the following code is present: The button labeled Data Import is displayed.... <button mat-menu-item (click)="download()"> <mat-icon>cloud_download</mat-icon> <span>Data Imp ...

The second guard in Angular 5 (also known as Angular 2+) does not pause to allow the first guard to complete an HTTP request

In my application, I have implemented two guards - AuthGuard for logged in users and AdminGuard for admins. The issue arises when trying to access a route that requires both guards. The problem is that the AdminGuard does not wait for the AuthGuard to fini ...

I'm experiencing an issue with redirect in Nextjs that's causing an error message to appear. The error reads: "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

I'm currently diving into the world of NextJS and working on creating a simple recipe application. Utilizing the new App Router has been smooth sailing for the most part, except for one hiccup with the login function. After successfully logging in (us ...

Converting a typename to a type in TypeScript

Is there a way to cast a string with a typename to a type without an explicit mapping in order to use it for an angular component factory? When there is a mapping, the process is straightforward: public readonly typeMap: Map<string, Type<{}>> ...

Retrieve individual data record from AngularFireDatabase

Welcome to my blog showcasing various screenshots: https://i.sstatic.net/cAtci.png My current focus is on retrieving a single course using its id, and I have the following code snippet for that purpose: Service: getSingle(uid: string) { return thi ...

Angular 4 HTTP Requests Failing to Retrieve JSON Data

I am currently working with the following method in my Typescript: allPowerPlants(onlyActive: boolean = false, page: number = 1): PowerPlant[] { const params: string = [ `onlyActive=${onlyActive}`, `page=${page}` ].join('&&apo ...

Creating a pop-up effect for a div in the center of a table cell using HTML and CSS

I am currently working with Angular and facing a challenge where I need to display a div like a popup in a table cell when clicked. Despite having the click event logic in place, I am unsure of how to achieve this without using external libraries such as B ...

Why does the private map function in the class fail while the global function succeeds?

Issues arise when calling the map() function on a parsed JSON object within the mapStocks() function. Placing the toStock() function inside the StockService class results in failure, whereas declaring it as a "global" function outside the class works witho ...

Guide to incorporating external code in InversifyJS without direct control

I'm wondering if it's feasible to add classes that are not editable. Inversify seems to rely heavily on annotations and decorators, but I'm curious if there is an alternative method. ...

Is it possible to trigger the setState() function of a parent component when a child component is clicked?

Hey there, I'm a new developer diving into the world of Reactjs. I've been working on setting up a Todo app but struggling to configure it just right. My main challenge is getting a button to add items to the list when submitted. I think I'm ...