MisterniceGuy
MisterniceGuy

Reputation: 1786

How can i filter and map with Switch Map in one statement?

I have an emitter which emits an array of object which look like this below example.

ServerDropdownOption
name: "Just Closed Buyers"
selected: true
value: "leadbucket::07727388-500A-4ED0-BB5A-1BB4718F1AFC"
__proto__: Object

the code i am using uses switchMap to only return the value of each object.

this.chipsSelect.multiSelectBox.onSave
  pipe(
  takeWhile(_ => this.alive),
  filter((tag) => tag.selected === 'true'),
  switchMap(updatedSelection => this.contactsService.updateBuckets(this.contactId, updatedSelection.map(tag => tag.value))) )
  .subscribe();

what i need now is to also filter based on the selected value and also return the ones where that value is true. Problem is that it generates the folowing error.

Property 'selected' does not exist on type 'IOptionMultiSelectBox[]'

export interface IOptionMultiSelectBox {
    name: string;
    value: any;
    selected: boolean;
}

so my IOptionMultiSelectBox has the selected property but the dat returned from my observable is an array of objects. So how can i fix that so the filter works ?

Upvotes: 2

Views: 1312

Answers (2)

MisterniceGuy
MisterniceGuy

Reputation: 1786

I made it work by actually applying the filter before the emit process

save(optionsList: IOptionMultiSelectBox[]) {
this.onSave.emit(optionsList.filter(data => data.selected === true));
this.toggleDirective.close();
}

In which case it did not complain about the selected property

Upvotes: 0

AVJT82
AVJT82

Reputation: 73337

instead of rxjs filter, use map and then use JS array.prototype filter to fetch the selected which are true:

this.chipsSelect.multiSelectBox.onSave
  pipe(
    takeWhile(_ => this.alive),
    map((tags: IOptionMultiSelectBox[]) => tags.filter(tag => tag.selected == true)),
    // .....

Upvotes: 3

Related Questions