Home > database >  How can I search for values contained in observable data fields?
How can I search for values contained in observable data fields?

Time:10-03

 public rows$: Observable<any[]> = combineLatest([
    this.items$,
    this.term$,
  ]).pipe(
    map(([items, term]) =>
      items.filter(
        (item) =>
          term === "" ||
          item.product_name === term ||
          item.product_detail === term 

If we think in database logic, it can be interpreted as the use of like expression. Ex. Contains includes

CodePudding user response:

You can use Object.values.includes to search for a value in an object like this

 public rows$: Observable<any[]> = combineLatest([
    this.items$,
    this.term$,
  ]).pipe(
    map(([items, term]) =>  items.filter((item) => Object.values.includes(term)))

CodePudding user response:

If your term$ value is a string, you could make use of includes(). If your term is an object containing properties, for example, you would have to access properties instead. Using map() we return array [] of items$ which satisfied filter() criteria. Result below would return 2 obj's where product_name contains iPhone.

   items$ = of([
    {
      id: 1,
      product_name: 'iPhone 9',
      product_detail: 'An apple mobile which is nothing like apple',
      price: 549,
      discountPercentage: 12.96,
    },
    {
      id: 2,
      product_name: 'iPhone X',
      product_detail:
        'SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...',
      price: 899,
      discountPercentage: 17.94,
    },
    {
      id: 3,
      product_name: 'Samsung Universe 9',
      product_detail:
        "Samsung's new variant which goes beyond Galaxy to the Universe",
      price: 1249,
      discountPercentage: 15.46,
    },
  ]);
  term$ = of('iPhone');

  public rows$: Observable<any[]> = combineLatest([
    this.items$,
    this.term$,
  ]).pipe(
    map(([items, term]) =>
      items.filter(
        (item) =>
          item.product_name.includes(term) || item.product_detail.includes(term)
      )
    )
  );

Working example: https://stackblitz.com/edit/angular-ivy-hima7q?file=src/app/app.component.ts,src/app/app.component.html

  • Related