iadducchio3
iadducchio3

Reputation: 75

RXJS better way to map and filter array inside of Observable<object>

This is a very simple version of what I am trying to accomplish. Currently it is working as intended but I was just wondering if there a shorter/cleaner way to implement the operators inside of pipe()

Current Behavior: call pipe on an observable that contains a property with array 'Items'. Inside of the pipe, filter, sort and then publish the items to a behavior subject.

  public items$: BehaviorSubject

  public testObservable = () =>
    of({
      Test: '123',
      Properties: 'props',
      Items: [
        { key: 1, val: 'test1' },
        { key: 2, val: 'test2' },
        { key: 3, val: 'test3' }
      ]
    });

  testMethod() {
    this.testObservable()
      .pipe(
        pluck('Items'),
        map(items => items.filter(item => item.key != 2)),
        map(items => items.sort((a, b) => (a.key > b.key ? 1 : -1))),
        tap(items => { this.items$.next(items) })
      );

Upvotes: 0

Views: 1104

Answers (1)

Totati
Totati

Reputation: 1592

Well I you could write just

this.testObservable()
  .pipe(
    map(value => 
        value.items.filter(item => item.key != 2)
             .sort((a, b) => (a.key > b.key ? 1 : -1))
    ),
    tap(this.items$.next)
  )

Upvotes: 1

Related Questions