简体   繁体   中英

how to turn an observable object into an observable array

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.

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])
  )
);
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;
  })
);

}

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM