fxck
fxck

Reputation: 4908

rxjs5 - filtering array of objects by observable that each object contains

I have an array that looks like this

[
  {
    name: 'foo'
    filter: Observable.of(true)
  },
  {
    name: 'bar'
    filter: Observable.of(false)
  }
]

and I want to return only items whose filter resolves in true, how would I do that in the most efficient and reactive way? I'm using rxjs5 beta2.


Note that it's a pseudocode for simplicity sake, in my real case filter is actually an object, that is passed to a validation function, which returns an observable that resolves in true or false.

Upvotes: 0

Views: 3205

Answers (2)

Calvin Belden
Calvin Belden

Reputation: 3104

You can flatMap each item in the array to an Observable stream that will emit a version of the item that replaced the filter property of type Observable<bool> with a bool property.

const data$ = Rx.Observable.from(arr)

  // Convert each item's filter property to type bool
  .flatMap(x => x.filter.map(condition => Object.assign({}, x, { filter: condition })))

  // Now we can just filter over the filter property, which is of type bool.
  .filter(x => x.filter)

  // Each item emitted will have a filter value of true
  .subscribe(x => console.log(x));

Upvotes: 1

jamesRH
jamesRH

Reputation: 440

There are two things in RxJS 4 that make this easy: map and Rx.helpers.defaultComparer. first map sends each item from the iterable separately and the defaultComparer will do the deep check for you.

var comparer = Rx.helpers.defaultComparer;
const Observable = Rx.Observable;

const arr = [
  {
    name: 'foo',
    filter: Observable.of(true)
  },
  {
    name: 'bar',
    filter: Observable.of(false)
  }
];

const data$ = Observable.from(arr)
  .map(each => each)
  .filter(each => comparer(each.filter, Observable.of(true)))
  .subscribe(x => console.log(x));

// prints Object {name: "foo", filter: FromArrayObservable} to my console

For some reason this defaultComparer is not in five at this time. Maybe there is a new name for the helper because it is not said to be deprecated in 4 or maybe it has not be migrated over yet or is not at .helpers.

Upvotes: 0

Related Questions