Home > Back-end >  how to turn an observable object into an observable array
how to turn an observable object into an observable array

Time:05-19

I have this observable object in my angular project that has this type:

  export interface FavoritesResponse {
    wallet: boolean;
    deposit: boolean;
    withdraw: boolean;
    transfer: boolean;
    exchange: boolean;
    ticket: boolean;
    account: boolean;
  }

I want to extract an array from this object with only the properties that have the value true.

So for example if my favorites object looks like this:

  favorites$ = {
    wallet: true;
    deposit: true;
    withdraw: false;
    transfer: false;
    exchange: false;
    ticket: true;
    account: true;
  }

I want to have my enabledFavorites$ look like this:

  enabledFavorites$ = [
    wallet,
    deposit,
    ticket,
    account
  ]

as in, turn it into an array and only have the keys that had the value of true. How can I do this? I know the solution probably contains an rxjs pipe, map but I don't know what I should be doing exactly.

CodePudding user response:

If you mean to say the observable emits an object of type FavoritesResponse and you wish to transform the emission to an array of it's keys only with value true, you could use

  1. RxJS map operator to transform the incoming object
  2. Native JS methods Object.keys() with Array#filter to perform the actual transformation
enabledFavorites$: Observable<string[]> = favorites$.pipe(
  map((favs: FavoritesResponse) => 
    Object.keys(favs).filter((key: string) => !!favs[key])
  )
);

CodePudding user response:

get favoritesArray$(): Observable<string[]> {
return this.favoritesSettings$.pipe(
  map((favorites) => {
    const _items = Object.keys(favorites);
    const _result: string[] = [];

    _items.forEach((item) => {
      if (!!(favorites as any)[item]) {
        _result.push(item);
      }
    });

    return _result;
  })
);

}

CodePudding user response:

So I guess that you want is convert from Observable<FavoritesResponse> to Observable<string[]> with the string[] containing the keys checked.

One way could be:

  const enabledFav$ = favOptions$.pipe(
    map(resp => {
      let result = [];
      Object.keys(resp).forEach(key => {
        if (resp.key) {
          result.push(key);
        }
      });
      return result;
    })
  );

I dont know the scenario but this is basically the code.

Here enabledFav$is Observable<string[]> and favOptions$ is Observable<FavoritesResponse>

  • Related