Reputation: 947
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.
Upvotes: 1
Views: 361
Reputation: 31105
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
map
operator to transform the incoming objectObject.keys()
with Array#filter
to perform the actual transformationenabledFavorites$: Observable<string[]> = favorites$.pipe(
map((favs: FavoritesResponse) =>
Object.keys(favs).filter((key: string) => !!favs[key])
)
);
Upvotes: 4
Reputation: 978
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>
Upvotes: 0
Reputation: 1
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;
})
);
}
Upvotes: 0