I have
- An array of objects
- A function
permission(obj): Promise<boolean>
Is there a simpler way to filter this array based on the promise result?
I've experimented with different approaches, but the closest I got was
of(arr).pipe(
switchMap(items =>
from(items)
.pipe(
mergeMap(item =>
fromPromise(permission(item)).pipe(
map(show => ({show, item})),
filter(data => data.show),
map(data => data.item)
)
))
));
However, this method seems overly complex.
I was hoping for a more concise solution like
of(arr).pipe(filterByPromise(permission))
, but I'm struggling to simplify it.
I have created a Stackblitz example here
StackBlitz code
import { of } from 'rxjs';
import { map, filter } from 'rxjs/operators';
// Mocked 3rd party function
function visible(obj): Promise<boolean> {
return new Promise(resolve => {
const shouldShow = obj.shouldShow < 30;
resolve(shouldShow);
});
}
const arr = [{
shouldShow: 39,
data1: 'abc',
data2: 'bcd'
}, {
shouldShow: 22,
data1: 'cde',
data2: 'def'
}];
of(arr).pipe(
filter(obj => visible(obj))
).subscribe(result => console.log(result));