creating a map of a collection of elements

I'm seeking suggestions on how to achieve this task. The getAllData function returns an array of objects, and I need to iterate through each object resulting from getAllData and extract the id of objects with Type-A. Subsequently, I aim to use each id to query getDealDetails based on the Id.

If there is a matching id in getDealDetails and it has a result, I want to retrieve the TypeValues summary value from the getDealDetails result and add a new key-value pair to the res items obtained from getAllData. The new key will be "dataValue:" and the value will be the data fetched from TypeValues summary.

The final result should resemble the sample object provided below. For instance, if there is a match with the id 248, then append the specified dataValue.

Thank you for any assistance and insights.

[
        {
            "id": 248,
            "name": "248-A",
            "Type": "Type-A",
            "fileName": null,
            "serverFileName": null,
            "size": null,
            "absoluteUri": null,
            "sentTo": null,
            "dataValue": "Summary Data"
        },
          {
            "id": 249,
            "name": "249-A",
            "Type": "Type-A",
            "fileName": null,
            "serverFileName": null,
            "size": null,
            "absoluteUri": null,
            "sentTo": null
        },
     {
            "id": 243,
            "name": "243-Z",
            "Type": "Type-Z",
            "fileName": null,
            "serverFileName": null,
            "size": null,
            "absoluteUri": null,
            "sentTo": null
        },
    ]

Here's the code snippet fetching data and the res items:

private getAllData() {
    this.searchInput = '';
    const status = 'Draft'
    this.isLoading = true;
    this.dealService
      .getAllData(
        status,
        this.accountId,
        this.transaction.id,
        this.table.pageIndex + 1,
        this.table.pageSize,
        this.searchInput,
        this.table.sortParams,
        this.table.sortDirs
      )
      .pipe(finalize(() => (this.isLoading = false)))
      .subscribe((res) => {
        console.log("ress " , res.items)
        this.getDealDetails(res.items.id);
      }, (err) => this.notificationService.showError(err)
    );
  }

Below are sample result items obtained from getAllData:

[
    {
        "id": 248,
        "name": "248-A",
        "Type": "Type-A",
        "fileName": null,
        "serverFileName": null,
        "size": null,
        "absoluteUri": null,
        "sentTo": null
    },
      {
        "id": 249,
        "name": "249-A",
        "Type": "Type-A",
        "fileName": null,
        "serverFileName": null,
        "size": null,
        "absoluteUri": null,
        "sentTo": null
    },
 {
        "id": 243,
        "name": "243-Z",
        "Type": "Type-Z",
        "fileName": null,
        "serverFileName": null,
        "size": null,
        "absoluteUri": null,
        "sentTo": null
    },
]

Code snippet for fetching details:

getDetails(Id: number) {
    this.service.getDetails(Id)
    .subscribe(
      res =>{  
        console.log("res.data;" , res.data)            
      },
      err =>{
        console.log('Error getting deal details');
      }
    )
   }

Sample result from getDetails:

{
    "id": 248,
    "name": "248-A",
    "fileName": null,
    "serverFileName": null,
    "size": null,
    "absoluteUri": null,
    "sentTo": null,
    "TypeValues": {
        "id": 24,
        "name": "248-A",
        "summary": "Summary Data",
   
        }
    }
}

Answer №1

It seems like your goal is to retrieve data from the initial query and then perform multiple additional queries to enrich the data further. I recommend checking out the RxJS documentation, specifically focusing on operators such as combineAll, concatAll, and combineLatest.

Below is an example of how you could approach this task. However, it appears that there are other significant issues in your code snippet, such as referencing res.data instead of res.items and attempting to access res.items.id within an array. Here is a pseudo-code representation:


  private getAllData() {
   
    this.isLoading = true;
    this.dealService
      .getAllData(
        status,
        this.accountId,
        this.transaction.id,
        this.table.pageIndex + 1,
        this.table.pageSize,
        this.searchInput,
        this.table.sortParams,
        this.table.sortDirs
      )
      .pipe(
        map((res: any) => res.items.map(
          // Fetch details for each item and merge them with a new copy of the item 
          item => this.getDealDetails(item.id).pipe(
            map((getDealDetailsResponse: any) =>
              ({
                ...item,
                ...{ dataValue: getDealDetailsResponse.data.TypeValues }
              })
            )
          ))
        ),
        // Combine the array of observables above into a single observable 
        // and emit the result when all operations have completed
        combineAll()
      ).subscribe((mergedResults) => {
        console.log(mergedResults);
      });      
  }

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 Javascript loop is not returning true even when the two strings are equal

While examining an array to determine if it contains a specific word, I noticed that the loop always returns 'false' even though it should be 'true'. Upon logging the comparison between the word I am looking for (collectionNameLookingFo ...

A method for setting values independently of [(ngModel)] within an *ngFor loop and selecting an HTML tag

I am encountering an issue with [(ngModel)], as it is syncing all my selections to the same variable. My variable is selectStations = []; Therefore, when I choose an option in one select element, it updates all select elements to have the same selected o ...

Ways to remove specific characters from the escape() function in express-validators

When using the check method from express-validator to validate user input, I'm curious if there's a way to exclude certain characters from the test. For example, currently I have: check("profile.about").trim().escape() This code snippet convert ...

Trouble with two dropdown selections in Angular and preset values

I am encountering an issue with a select input in angular 7. The scenario involves having 2 selects where selecting an option in the second select populates the corresponding values in the first select. The first select should display a default placeholder ...

What are some tips to ensure that my JavaScript submissions always execute correctly?

I'm facing an issue with uploading a canvas draw image using JavaScript in a .php file. The SQL data submission to the database always works, but the upload of the canvas draw image doesn't consistently function. This problem occurs specifically ...

Twilio SMS Notification: The Class extension value provided is not a valid constructor or null

When attempting to utilize Twilio for sending SMS messages in a Vue.js project, I encountered an error while accessing Tools -> Developer Tools. <template> <div> <input type="text" v-model="to" placeholder="Ph ...

Initiate button click event of a Vue.js application via a Chrome extension automatically

I'm currently working on a Google Chrome extension that interacts with a third party website built using Vue.js. My goal is to programmatically trigger a click event on a particular button within the webpage. However, when I attempt to do this using ...

What is the best way to obtain the most recent value from an observable or subject without needing to subscribe?

I have created a basic Store service where I use the init method to send an http get request and retrieve courses. My goal is to update a specific course by its courseId with some changes. To achieve this, I have implemented a save method in the store. Ho ...

Reduce the value of a Perl scalar variable each time an ajax script is executed

My webpage features a header with a notification button that indicates the count of unarchived notifications using this Perl code snippet: @notices_posts = System::Notice->fetch_all_posts(userid => $user->userid(), visible => 1); @regular_post ...

Is it possible to implement custom PDF rendering in ng2-pdf-viewer for handling large PDF files?

I am currently utilizing the ng2-pdf-viewer to showcase a pdf within my angular application. However, I've noticed that the viewer only displays the pdf after it has been fully downloaded from the server. The server sends the pdf data to me in the for ...

How can I customize the color of grayed-out days in Fullcalendar's validRange?

Hello there, I am currently using fullcalendar version 5.10.1 for my project and I am looking to change the color of already passed days to a more grayish tone as shown in the picture. Unfortunately, I am unable to utilize Ajax and can only use CSS styles. ...

React's `setState` function seems to be failing to update my rendered catalog

Managing a shopping catalog where checkboxes determine the rendered products. The list of filters serves as both the menu options and state variables. The actual products in the products list are displayed based on the selected categories. const filters ...

Error: Functionality cannot be achieved

Looking for assistance in resolving this issue. Currently, I am attempting to register a new user and need to verify if the username already exists or not. Below is the factory code used for this purpose: .factory('accountService', function($res ...

Navigating with Three.JS FPS controls by moving left and right

Currently, I am working on a demo to check player controls for a FPS game. The camera rotation is controlled by the mouse, and the player can move using W-A-S-D keys. However, I am facing an issue with implementing movement left and right relative to the d ...

Is it possible to call a service within an NgFor loop in Ionic/Angular 2?

I am facing an issue with my ngFor directive. Here is the code snippet: <ion-card *ngFor="let review of reviews"> <ion-card-content> {{getUserName(review.user_ID)}} </ion-card-content> </ion-card> The challenge I a ...

Having trouble retrieving the chosen option from the radio button list

I am struggling with a radiobutton list <asp:RadioButtonList CssClass="radioLable" ID="rbListPointsCat" runat="server" RepeatDirection="Horizontal" AutoPostBack="true" OnSelectedIndexChanged="rbListPointsCat_SelectedIndexChanged" ...

Using Jquery and Ajax to add information to a database

One of the challenges I'm facing involves a page with three forms, each containing separate variables that need to be inserted into a MySQL database for viewing. My current script is working fine, even though I am aware that `mySql_` is deprecated but ...

AngularJS: Issue with JQuery Slider not Updating Scope Value

I am currently working on a project using AngularJS and I have integrated a jQuery slider into it. However, I am facing an issue where I need to change the value of a select box which is defined in a $scope array, but the functionality is not working as ex ...

Having trouble converting customized tabs into Bootstrap navigation tabs?

Creating custom tabs with unique tab logic <!-- <lntds-tabs [selectedIndex]="selectedTabIndex" (selectedTabChange)="tabChanged($event)"> --> <!-- <lntds-tab class="custom-tab-group lntdstabsco ...

Prevent submission of Angular form while still displaying errors upon clicking

My goal is to implement a form using Angular, where the submit button remains disabled until the form is valid. When the user clicks the button, the background color of any invalid input should change along with displaying an alert message below the form. ...