tips for converting a single observable item into an observable list

Within my Angular project, there exists an observable object with the following structure:

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

My goal is to create an array from this object that only includes properties with a value of true.

For instance, if my favorites object is as follows:

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

I aim to transform my enabledFavorites$ to match this format:

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

In other words, convert it into an array containing only the keys that held a value of true. How can I achieve this? While I believe the solution involves utilizing an rxjs pipe and map, the exact implementation eludes me.

Answer №1

If you're looking to convert the output of the observable, which emits an object of type FavoritesResponse, into an array containing only its true values based on keys, you can achieve this through:

  1. Using RxJS map operator to transform the incoming object
  2. Applying native JS methods like Object.keys() along with Array#filter to carry out the conversion process
enabledFavorites$: Observable<string[]> = favorites$.pipe(
  map((favs: FavoritesResponse) => 
    Object.keys(favs).filter((key: string) => !!favs[key])
  )
);

Answer №2

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

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

    return _result;
  })
);

}

Answer №3

It seems like what you're trying to do is convert from

Observable<FavoritesResponse>
to Observable<string[]>, where the string[] contains the checked keys.

One approach could be:

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

I'm not sure about the specific scenario, but this should give you an idea of the code structure.

Here, enabledFav$ represents Observable<string[]>, and favOptions$ represents

Observable<FavoritesResponse>
.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to divide percentages accurately in Angular?

I am currently working on splitting percentages dynamically with Angular. For example, if txtBox1 has 75%, I want to split the remaining 25% between txt2 and txt3. If I change txt1 to 50%, then I want txt2 and txt3 each to receive 25%. The values may vary, ...

Is it true that all events in JavaScript go through capturing and bubbling phases?

My current project involves binding one eventListener to an <audio> element for the play event and another eventListener to its parent element for the same event. I've observed that the callback for the child element always gets executed, while ...

Can you explain the significance of the "@" symbol in the `import from '@/some/path'` statement?

When I use IntelliJ IDEA to develop a web application in TypeScript, the autocomplete feature suggests imports from other files within my project like this: import {Symbol} from '@/components/Symbol'; I am curious about the significance of the @ ...

Issue with Three.js failing to display textures

I'm a beginner with three.js and I'm struggling to get my texture to render properly in my scene. Despite following the documentation closely, all I see is a blank canvas with no errors in the console. Can anyone offer any guidance on why my code ...

having trouble with my lambda function reading the basic json object

I recently joined Lambda and have been attempting to create a simple JSON object. However, I keep encountering an error that says "parsing error, unexpected token." Here is my code, which I have verified to be valid JSON: { "metadata": { ...

The POST variable consistently remains void

The approach I am using to handle the data sent with jquery.ajax involves sending an empty string by default. Whenever there is a change, I monitor the input for changes and resend the data. Everything seems to work fine in the console, but in PHP, $this-& ...

Encountering a peculiar problem with the Bootstrap Carousel where the first slide fails to load

There seems to be an issue with the bootstrap carousel where the first slide appears empty initially, but once you slide to the second slide it starts working fine. Navigating through all slides is still possible. <div id="mediakit_carousel" class="car ...

using JavaScript to send numerous text box values to various views

I have a dilemma with passing values between two views. In View1, there are text boxes for entering basic information. After the customer enters this data and clicks on 'add more details', I want to transfer these details to the text boxes in Vie ...

I'm struggling to understand the reasoning behind the 'undefined' error occurring in the Google Maps distance service

Currently facing a puzzling issue with an 'undefined' exception. Developing a tool to track distance traveled between two locations, leveraging Google Maps distance matrix. Upon selecting a vehicle, entering an origin and destination, and clickin ...

Steps for generating data with Typescript Sequelize model without specifying an id:

Currently, I am utilizing Sequelize in conjunction with Typescript and facing a challenge when attempting to execute the Course.create() method without explicitly specifying an id field. Below is the Course model for reference: import { DataTypes, Model, O ...

Testing Angular 4 routing with router.url

Is there a way to simulate router.url in Angular 4 unit testing? In my component, I'm using router.url in the ngOnint function but in my test, the value for router.url is always '/'. ...

Locate the position of a substring within a Uint8Array

I'm working with a Uint8Array that contains the content of a PDF file. My goal is to locate a specific string within this array in order to insert additional content at that particular position. My current approach involves converting the Uint8Array ...

Observing modifications in the database is possible after executing the setInterval function

I am using a JavaScript function that runs every 4 seconds with setInterval. Once this function is executed for the first time, it calls an ajax request and changes a column value in the database. I want to know how I can check if this value has been succe ...

Error in Angular Due to Circular Reference in JSON

I'm currently working on integrating a tree structure in AngularJS. The goal is to construct the tree by dynamically adding nodes based on user input from an Angular Select element. Here is the specific operation I'm trying to accomplish: var a ...

Tips for detecting the existence of scrollbar on a webpage and retrieving its coordinates

I am working on a web page where I need to dynamically retrieve the scroll coordinates of the page. If a page has multiple scrolls, I should be able to get the respective scroll coordinates for each. The functionality needs to adjust based on the specifi ...

Positioning Images in Tailwind Modals

I'm currently working on building a modal using Tailwind in Vue, but I've run into some challenges with aligning the elements inside the modal as desired. I've experimented with removing certain Tailwind classes and have tried implementing ...

Obtaining the id in JavaScript from PHP to display information

This is the code I've written: <textarea id="summernote<?php echo $u->id ?>" name="isi" placeholder="Write here" style="width: 100%; height: 100px !important; font-size: 14px; line-height: 18px; border: ...

Hover and hover-off functions in navigation menu

html <div class="hidden-nav"> <h4>lorem</h4> <ul class="decor-menu-list"> <li><a href="#">123</a></li> <li><a href="#">123</a></li> <li><a hre ...

Unexpected server failure when connecting via socket.io to Node.js http-proxy

I'm encountering an issue with my Nodejs proxy server related to the dreaded socket hang up error. The server crashes every time I refresh the browser on 'app.example.com'. The connection seems fine and the page loads correctly, but the cra ...

Error in ReactJS: Attempting to access property 'preventDefault' of an undefined value

Looking to implement a simple onClick event/function in ReactJS. Upon clicking the button, I intend to execute a function named "onClick", but I encounter this error message in the console: app.js:62 Uncaught TypeError: Cannot read property 'prevent ...