Home > Enterprise >  How to iterate through array of type Observable<Type[]> or filter this array which is already
How to iterate through array of type Observable<Type[]> or filter this array which is already

Time:01-14

I have an object of type Observable<Cat[]> which is already having data, following is the type of test

export interface Cat {
    id: number,
    name: string,
    description: string,
    isActive: true
}

I want to filter it and select all records which has name start from 'ar' output must be only list of name.

CodePudding user response:

You can use the map operator in a pipe to filter the corresponding elements before displaying it : The Angular model :

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  filter: string = 'test';

  //your observable data
  data = of([
    {text: 'test_1'},
    {text: 'not corresponding'},
    {text: 'test'},
  ])
  .pipe(
    map((data) => data.filter(row => row.text.startsWith(this.filter)))
  );
}

the view :

<p *ngFor="let item of data | async">
  {{ item.text }}
</p>

CodePudding user response:

To filter an array of type Observable<Type[]>, you can use the filter() operator provided by the RxJS library. Here's an example of how you can use it:

this.observableCats.pipe(
  filter((cats: Cat[]) => {
    return cats.filter(cat => cat.name.startsWith('ar'));
  })
).subscribe(filteredCats => {
  console.log(filteredCats);
});

You can also use the map() operator to achieve the same result as following:

this.observableCats.pipe(
  map((cats: Cat[]) => {
    return cats.filter(cat => cat.name.startsWith('ar'));
  })
).subscribe(filteredCats => {
  console.log(filteredCats);
});

In this example, the filter() operator filters the cats array and returns an array of cats whose name property starts with 'ar'. The filtered array is then passed to the subscribe() method, where you can access it and do whatever you need with it.

You could also use the Array.prototype.filter() to filter the data if you are not using rxjs or in case you have the data already.

let filteredCats = this.cats.filter(cat => cat.name.startsWith('ar'));

Hope this helps!

  • Related