Check that the elements within the array are present in the observable array

I need to confirm whether the items in the array below:

const payment1: Payment = new Payment('1000'); // 1000 = id
const payment2: Payment = new Payment('1001');

const paymentArray: Payment[];
paymentArray.push(payment1, payment2);

are present in my observable array:

payments$: Observable<Payment[]>;

What I want is a boolean value (non-observable) as a result.

I have attempted using filter pipe and map but have not been successful:

this.paymentArray.forEach(element => {
  this.payments$.pipe(map(payments => payments.filter(payment => payment.id === element['id'])));
});

Answer №1

when dealing with an array of objects, it is beneficial to create a map of those elements in order to efficiently compare them within a filter function.

ngOnInit() {

    this.idsToFind = ['1000', '1231', '2323'];
    const paymentArray: Payment[] = [];
    const payment1: Payment = new Payment('1000'); // 1000 = id
    const payment2: Payment = new Payment('1001');

    paymentArray.push(payment1, payment2);

    this.payments$ = of(paymentArray);

    const idsMap = this.idsToFind.reduce(
      (a, b) => { return { ...a, [b]: true } }, {}
    );
    console.log(idsMap);

    this.payments$
      .pipe(
        map((payments) =>
          payments.filter(
            (payment: Payment) => idsMap[payment.id])
        )
      )
      .subscribe((missings) => console.log(missings));

  }

Answer №2

If you're looking to achieve a similar functionality, check out the following code example along with my stackblitz demo: https://stackblitz.com/edit/angular-yg1b11

import { Component, OnInit } from '@angular/core';
import { Observable, of } from 'rxjs';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  payments$: Observable<Payment[]>;
  idToFind = '';
  isFounded = false;

  ngOnInit() {

    this.idToFind = '1000'
    const paymentArray: Payment[] = [];
    const payment1: Payment = new Payment('1000'); // 1000 = id
    const payment2: Payment = new Payment('1001');

    paymentArray.push(payment1, payment2);

    this.payments$ = of(paymentArray);

    this.payments$.subscribe((x) => {
      x.forEach(element => {
        if (element.id == this.idToFind) {
          this.isFounded = true;
        }
      })
    })

  }

}

export class Payment {
  id: string;

  constructor(id: string) {
    this.id = id;
  }

}

Answer №3

To retrieve an observable result, you can utilize the toPromise method in the following way:

const amount1: string = '100';
const amount2: string = '200';

const amountsArray: string[] = [];
amountsArray.push(amount1, amount2);

const amounts$ = of(['100', '200', '300']);

const allIncluded = await from(amountsArray).pipe(withLatestFrom(amounts$), every(([item, amounts]) => amounts.includes(item))).toPromise();

Answer №4

To successfully process the observable data, you must pass it through a pipe and map the stream accordingly. Within the callback function of the map method, ensure that each element in the paymentArray is present in the provided value.

Refer to this illustrative example:

const ids = paymentArray.map(payment => payment.id);

this.payments$.pipe(
  map(paymentsList => {
    const paymentIds = paymentsList.map(payment => payment.id);
    return ids.every(id => paymentIds.includes(id));
  })
)
// The `value` output will display either true or false after the validations.
.subscribe(value => console.log(value));

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

Enhancing Angular functionality with the addition of values to an array in a separate component

I need help with adding a value to an array in the 2nd component when a button in the 1st component is clicked. I am working on Angular 4. How can I achieve this? @Component({ selector: 'app-sibling', template: ` {{message}} <butt ...

Submitting a Form with Request Body using Angular 2

I am struggling to figure out how to send a form to an API with the body. I have managed to hard code the body so far, but I really need to dynamically retrieve values from the form and send them as the body to the API. Can someone please guide me on how t ...

Advantages of incorporating types through imports versus relying solely on declaration files in Typescript

We are currently in the process of switching from plain JavaScript to TypeScript. One aspect that I personally find frustrating is the need to import types. In my opinion, importing types serves no real purpose other than cluttering up the import section ...

Angular 2: Triggering the "open" event for a Bootstrap dropdown

I am currently in the process of developing a directive that will trigger a Bootstrap dropdown to open when clicked and close it when the mouse leaves. Below is the code for the dropdown directive: import {Directive, HostBinding, HostListener} from ' ...

Placing a MongoDB query results in an increase of roughly 120MB in the total JS heap size

I'm puzzled by the fact that the heap size increases when I include a MongoDB database query in a function within my controller. Here is the code for my router: import { Router } from "express"; import profileController from '../contro ...

Tailoring Aurelia for .cshtml integration

I stumbled upon an informative article detailing the integration of Razor partials (cshtml) with aurelia. Despite my efforts, I encountered difficulty in getting the code to execute properly and was informed by Rob Eisenberg's comment that Convention ...

Do we require two-way binding to effectively exchange data between components in this situation?

I'm currently facing some challenges in updating data in a child component when new data is added from the parent component. Here's a snippet of my template: <ion-content> <app-feed-comments [comments]="comments" [userId]=& ...

No response data being displayed after Angular post request

After sending a POST request via Postman, I received the expected response with a status of 400. However, when I tried sending the same request using Angular's http.post in the browser, I only received a 400 error without any response data. https://i ...

Excessive recursion detected in the HttpInterceptor module

My application uses JWT tokens for authentication, with a random secure string inside the JWT and in the database to validate the token. When a user logs out, a new random string is generated and stored in the database, rendering the JWT invalid if the str ...

Unexpected silence from the Express web server

I am currently in the process of setting up my Angular application for Server Side Rendering using Angular Universal. Below is the JS file that has been generated by Angular Universal, with minor modifications made to the path and port: import 'zone ...

Transform Angular Material Table selection color with selection

Is it possible to customize the color of the selector in an Angular Material table when using selection? Learn more about it https://i.sstatic.net/5ZJQT.png ...

Guide on implementing ng2-completer with translation features

Recently delving into Angular, I'm experimenting with integrating the ng2-completer module alongside the TranslateModule. The issue arises when attempting to fetch JSON data from the server-side. The retrieved JSON structure is as follows: [{"id":10 ...

Error encountered during the deployment of Ionic 3 with TypeScript

After completing the development of my app, I ran it on ionic serve without any issues. However, when compiling the app, I encountered the following error message. Any assistance in resolving this matter would be greatly appreciated. [15:40:08] typescri ...

What is the best way to display toastr messages in an Angular application?

Can you guide me on how to include toastr in an angular app? Currently, I am enrolled in the Angular Fundamentals course and trying to use toastr.success within my export class: handleThumbnailClick(eventName){ toastr.success(eventName) } But, I kee ...

Issue with Angular 6: Unable to match nested routes

I am working on a project to test nested routing in Angular. While the app-routes are functioning correctly, I am encountering an error stating that the children "cannot match any routes". After checking other solutions, I am still confused due to version ...

Angular: Modify parent component's field using route

Hello everyone! I'm seeking assistance. In my Angular 10 application, I have a component called A. Within this component, there is a <router-outlet> and routes defined in the routes.ts file. My goal is to modify a variable (field) inside comp ...

The function called v1.isEqual is throwing a TypeError because it is not recognized as

When working on my NextJs/React project, I encountered an issue while using the useCollectionData hook. The problem arises when fetching posts from my firestore database, resulting in the error message TypeError: v1.isEqual is not a function Below is the ...

Encountered an error while attempting to install the @typescript-eslint/eslint-plugin

After starting the installation process for eslint plugins, I encountered an issue with @typescript-eslint/eslint-plugin. The plugin requires installation using--legacy-peer-deps, but this approach may introduce potential bugs by accepting an incorrect an ...

Working with JSON data in Typescript without specified keys

My goal is to extract the IssueId from the JSON data provided below: [ { "-MERcLq7nCj5c5gwpYih": {"CreateDate":"2020-08-11T08:27:13.300Z","Id":"-MERcLq7nCj5c5gwpYih","IssueId":"-ME3-t ...

Navigating through object keys in YupTrying to iterate through the keys of an

Looking for the best approach to iterate through dynamically created forms using Yup? In my application, users can add an infinite number of small forms that only ask for a client's name (required), surname, and age. I have used Formik to create them ...