Exploring nested JSON objects within an array using ngFor directive

My application uses Angular 6 and Firebase. I am trying to showcase a list of all appointments. Below is my approach:

service.ts

getRDV() {
  this.rdvList = this.firebase.list('/rdv');
  return this.rdvList;
}

Model:

export class RDV {
  key: string;
  date: string;
  heure: string;
  spe: string;
  uidpat: string;
  uid: string;
  status: string;
}

In ts :

export class ListComponent implements OnInit {

  rdvList: RDV[];

  constructor(
    private usersService: UsersService,
    private router: Router
  ) {}

  ngOnInit() {
    var x = this.usersService.getRDV();
    x.snapshotChanges().subscribe(item => {
      this.rdvList = [];
      item.forEach(element => {
        var y = element.payload.toJSON();
        y["$key"] = element.key;
        this.rdvList.push(y as RDV);
      })
      console.log(this.rdvList)
    })
  }

}

In Html :

<tr *ngFor="let rdv of rdvList| myfilter:term, let i = index">
  <div *ngFor="let item of rdvList.rdv.key">
    <td> {{item.$key}} </td>
    <td> {{item.uidpat}} </td>
    <td> {{item.date}} </td>
    <td> {{item.heure}} </td>
    <td> {{item.spe}} </td>
    <td> {{item.uid}} </td>
    <td> 
      <button class="btn btn-primary" (click)="onViewUser(user?.uid)">
        Choisir
      </button> 
    </td>
  </div>
</tr>

DATA STRUCTURE: https://i.sstatic.net/EfxWf.png

I am having trouble resolving the issue with the data structure. Should I consider changing how they are pushed into the table or utilize the template *ngfor to address the problem.

This is the JSON object from my console log

Answer №1

If you are looking to retrieve a list of Appointment Objects nested under the DATE keys, you will need to follow this mapping process:

export class ListComponent implements OnInit {

  ...

  ngOnInit() {
    var x = this.usersService.getRDV();
    x.snapshotChanges().subscribe(item => {
      const appointments = [];
      item.forEach(element => {
        var y = element.payload.toJSON();
        y["$key"] = element.key;
        appointments.push(y);
      });

      // Perform the operation here
      this.rdvList = appointments
        .flatMap(item => Object.values(item))
        .filter(item => typeof item === "object");

      console.log(this.rdvList)
    })
  }

}

The first flatMap function extracts all values from each object in the array, including appointment objects and date strings.

To filter out only the items that are of type Object, apply a filter to the results of the initial flatMap operation.

After applying these operations, your Appointment Objects will be stored in the rdvList property, which can then be accessed in your template using *ngFor.

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

Testing the MatDialog Component

Currently, I am in the process of creating a unit test for my confirmation modal that relies on MatDialog. The initial test I have set up is a simple one to ensure that the component is successfully created. Below is the code snippet from my spec file: im ...

Issue arises when trying to set object members using a callback function in Typescript

I am facing a peculiar issue that I have yet to unravel. My goal is to display a textbox component in Angular 2, where you can input a message, specify a button label, and define a callback function that will be triggered upon button click. Below is the c ...

Error when casting Typescript await toPromise

I encountered the following issue: export class FloorManagerComponent implements OnInit { public meta = { list: [], building: Building, loading: true, }; constructor( private router: Router, private ac ...

Customize Monaco Editor: Implementing Read-Only Sections

I am currently working on setting up the Monaco Editor so that specific sections of the text content are read-only. Specifically, I want the first and last lines to be read-only. See example below: public something(someArgument) { // This line is read-onl ...

To effectively run the Angular Compiler, it is necessary to have TypeScript version greater than or equal to 2.7.2 but less than 2.8.0. However, the system detected

I am encountering an error in my Angular application that reads: The Angular Compiler is asking for TypeScript version >=2.7.2 and <2.8.0, but it found 2.8.3 instead. When I attempt to downgrade TypeScript to the correct version by running: npm ...

Testing Angular NavigationEnd with Jest

Below is the code of my component that I want to test: allpages: Array<Page> = [ { name: 'Home', url: '/home' }, ]; constructor(private router: Router) { this.$routerEvent = this.router.events.subscribe((event: Event) => ...

Retrieve the template parameter from a generic type

While I have experience extracting string from string[], this particular scenario is proving to be quite challenging: type example<T = boolean> = true; // with just "example", how can I retrieve the template parameter "boolean" in this case? type T ...

Integration of Mocha with WebStorm

WebStorm offers a useful feature that adds a small arrow next to describe() and it() keywords when writing tests with Mocha, allowing for easy manual execution. However, there is a challenge: I require additional setup before each test, leading me to use ...

The app engine deployment is not implementing gzip compression on my content

Update Status An update is expected to be rolled out by the end of this month. I recently deployed a few websites on Google App Engine using standard environment NodeJS. It's been a bit delayed, but I'm hoping it's just something I overloo ...

What is the best way to create an interface that only allows keys to be a combination of values from a specific property found within each object of an array?

interface Filter { id: string; name: string; } type Filters = Filter[]; const filters = [{ id: 'f1', name: 'f1name'}, { id: 'f2', name: 'f2name'}] interface State { ... } const state = { f1: any, ...

Having difficulty connecting to the router within a container component for Angular2 routing

Presently, my code snippet looks like this: import { Router } from 'angular2/router'; @Component({...}) export class Index { constructor(public router: Router) { this.router.subscribe({...}); } } Although there are additional function ...

Angular 5 update causing 'NgModule not found' error

After attempting to upgrade my app to Angular 5, I encountered a series of bugs. Among them, there is one persistent issue that has me stumped. An uncaught error has surfaced: 'Unexpected value HttpClient imported by the module AppModuleShared. Ple ...

Setting options using the form group in dropdowns in Angular can greatly enhance the user experience

I have created a FormGroup called holidayform and set it up as follows: holidayform: FormGroup; this.holidayform = this.fb.group({ title: ['', [Validators.required]], entryDate: ['',], }) this.holidayform.patchValue ...

Performing operations on information within a map function

While using toLocaleString within this map, I encountered an issue where only one of the payment.amount's returned formatted as currency. {props.paymentDates.map((payment, index) => ( <tr key={"payment-" + index}> <td>{i ...

Using the rxjs repeatWhen operator within the http request pipeline to automatically resend the request if the expected response is not received

I am attempting to simplify my HTTP request pipeline by ensuring that if the response does not contain the required data in res.myCondition, I can use repeatWhen to make another call. However, it seems like I am not using repeatWhen correctly (Angular 8/ R ...

"Angular EventEmitter fails to return specified object, resulting in undefined

As I work on a school project, I've encountered a hurdle due to my lack of experience with Angular. My left-nav component includes multiple checkbox selections, and upon a user selecting one, an API call is made to retrieve all values for a specific " ...

The getAuth() helper found in the api directory's Clerk retrieves the following data: { userId: null }

I'm completely stuck here.. Currently working with the clerk and I am looking to access the userId of the current user using the getAuth() helper. For more information, refer to the docs: pages/api/example.ts import { getAuth } from "@clerk/n ...

Extract the JSON array data from the Service and process it within the Component

When passing a response from the Service to the Component for display on the UI, each value needs to be parsed and stored in a variable. This can be achieved by extracting values such as profileId, profileName, regionName, etc. from the response. [{"profi ...

Utilizing Typescript in tandem with an external library through es6 modules

Is there a recommended method for incorporating Typescript with non-module libraries like PixiJS and SortableJS without using webpacker? I'm looking to utilize es6 modules but want to avoid cumbersome solutions. What would be the best approach in this ...

Encountering Issue: Unable to locate control with the given name in Angular when generating Dynamic Form with FormGroup

As a beginner in Angular, I aim to develop a dynamic Survey Form that can adjust its questions and input types based on the area. These changes are fetched as JSON data through API calls. Here is the relevant code snippet: .ts File export class Maintenan ...