What is the best approach for presenting multiple entries with identical IDs in a table using Angular?

I obtained a JSON response in the following structure; https://jsonplaceholder.typicode.com/posts

My goal is to format the table to resemble the attached image structure.

However, my current implementation is displaying repeating user IDs. How can I adjust my code to achieve the desired output structure?

  <table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="row-border hover">
      <thead>
      <tr>
      <td>Sl No</td>
      <th>Title</th>
      <th>Body</th>
      </tr>
      </thead>
      <tbody>
      <tr *ngFor="let record of dataString;let i=index">
      <td>{{record.userId}}</td>
      <td>{{record.title}}</td>
      <td>{{record.body}}</td>
      </tr>
      </tbody>
    </table>

Answer №1

To effectively work with your api response, you'll need to parse it and structure a new object according to your requirements. One approach could be utilizing array methods for a 'group by' operation.

For instance, consider an object structure like user -> id: number, articles: article[]

public getUsers(): User[] {
    return this.http.get(URL).map(results => {
        const users: number[] = results
            .filter((item, index, self) => self.indexOf(item.userId) === index)
            .map(item => {
                return {
                    id: item.userId,
                    articles: results.filter(result => result.userId === item.userId)
                        .map(result => {
                            return {
                                id: result.id,
                                title: result.title,
                                body: result.body
                            } as Article
                        })
                } as User
            });
    })
}

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

The ng-select dropdown is experiencing issues on the user interface following an update to the newest versions of Angular 6

Recently, I made the transition of my application from Angular 5 to Angular 6. As part of the update process, I also upgraded ng-select to version 2.4.2, the latest one available on npm/GitHub. However, after the upgrade, the dropdown functionality seems ...

Can you explain the meaning of <T = {}>?

While browsing through the documentation, I came across this generic type: type GConstructor<T = {}> = new (...args: any[]) => T; https://www.typescriptlang.org/docs/handbook/mixins.html Above this line, there is a brief mention that it is a Gene ...

Using *ngIf to construct SVG icons in Angular 2 doesn't contribute to the DOM in any way

I am currently utilizing icoMoon to import a series of SVG icons. The structure of the html I'm trying to create using ngIf is as follows: <div class="contactIcon"> <svg class="icon icon-envelop"> <use xlink:href="symbol-d ...

Learn how to render a single element with multiple child elements within separate `<td>` tags in a table row using React

I'm just starting out with React and I have a code snippet that I'm using to render an HTML table in a component. Is there a more optimized way to achieve this? bodyItems = sorted.map((data) => [ data.employerName, data.sectors.map((sector ...

What is the best way to customize the styles of Material UI V5 Date Pickers?

Attempting to customize Mui X-Date-Pickers V5 through theme creation. This particular component is based on multiple layers. Interested in modifying the borderColor property, but it's currently set on the fieldset element, so need to navigate from Mu ...

Learning how to effectively incorporate two matSuffix mat-icons into an input field

I'm currently experiencing an issue where I need to add a cancel icon in the same line as the input field. The cancel icon should only be visible after some input has been entered. image description here Here's the code I've been working on ...

Retrieving subcollection data in Firestore using Angular

I am facing the challenge of extracting data from a subcollection within my database structure. Within my main collection products, there are documents that have a nested subcollection called reviews. products/prodID/reviews/reviewID Here is my interface ...

Angular 2 or more variable binding

In this demonstration, only the unit-object will be saved: <select id="unit" name="unit" #unit="ngModel" class="form-control" [(ngModel)]="iu.unit" (change)="onDropdownChangeUnit($event)"> <option *ngFor="let i of UI_Units" [ngV ...

Tips for successfully transferring the nested service and retrieving the response from an Angular factory to a controller

After making the Http Request and receiving the response from the first Service call, I then pass that response from the first service into the second service and receive the response back to the controller. Now that I have the response, I need to find a ...

Ways to eliminate unnecessary items from a JavaScript object array and generate a fresh array

My JavaScript object array contains the following attributes: [ { active: true conditionText: "Really try not to die. We cannot afford to lose people" conditionType: "CONDITION" id: 12 identifier: "A1" ...

Tips for simulating mouse events in Jasmine tests for Angular 2 or 4

New to Jasmine testing, I'm exploring how to test a directive that handles mouse events such as mouse down, up, and move. My main query is regarding passing mouse coordinates from the Jasmine spec to my directive in order to simulate the mouse events ...

The Angular Material Table is not showing any data on the screen

My challenge is to consolidate data from 4 different endpoints in order to generate a ListElement that will populate an angular material table. Despite receiving the correct data in my logs, the table remains empty. Interestingly, when I include a conditio ...

There was an issue retrieving the metadata for the bootstrap package using the git+ssh protocol

While attempting to install angular devkit and other dependencies using npm install, I encountered the following error message: Could not retrieve metadata for bootstrap@git+ssh://example@example.com/gios/Web-Standards-Bootstrap.git#05a343dddce91dd157702 ...

Troubleshooting nested form controls in Angular v12

When populating a dynamic form with data retrieved from the backend API, I encountered an issue with my code: sections: this.formBuilder.array([]) Within this code block, there is a nested array that is populated as follows: result.formSections.forEach(x ...

Create a TypeScript view component that encapsulates an HTMLElement for seamless integration with TweenMax

Looking to develop my own basic view component class that encompasses an HTMLElement or JQuery element, I want to be able to do something similar to this: var newComponent:CustomComponent = new CustomComponent($('#someDiv')); TweenMax.to(newCom ...

Ways to mimic an Angular subscription during a Jasmine test

I'm currently troubleshooting a unit test for my code (I'm not very experienced with Jasmine) after adding some subscriptions to a service. I'm encountering an issue where the subscriptions are coming up as undefined. I'm not entirely s ...

The formControl value is not being shown on the display

I am facing an issue with a form that has multiple fields created using formGroup and formControlName. The challenge arises when I launch the application and need to retrieve data from the back end to display it on the view. The specific problem I'm ...

Error: Failed to retrieve the name property of an undefined value within the Array.forEach method

Upon pressing the button to display the task pane, I encountered an error message in the console window that reads: "Uncaught (in promise) TypeError: Cannot read property 'name' of undefined". This error persists and I am unable to resolve or com ...

Challenges with Angular 4 service initialization

Having trouble with my authentication service. The constructor is being called 259 times when making an HTTP request, but only once when the call is removed. I am using a shared module to provide a unique instance of the service. Angular version: 4.4.4 C ...

Angular2 - Leveraging data to dynamically control radio buttons

I am looking to implement radio buttons in a form using Angular 2 with a data-driven approach. In my component, I have set up a form as follows: import { Component } from '@angular/core'; import {FormControl, FormGroup, Validators} from '@a ...