Leveraging the power of RXJS to efficiently transform and extract data from arrays within an Observable<object>

I am currently working on a project that involves utilizing the pipe() operator in an observable to filter, sort, and publish items. While it is functioning as intended, I am curious if there is a more concise way to implement these operators.

Current Scenario: The existing setup involves calling pipe on an observable that contains an array of 'Items'. Within the pipe, the items are filtered, sorted, and then published to a behavior subject.


public items$: BehaviorSubject

public testObservable = () =>
  of({
    Test: '123',
    Properties: 'props',
    Items: [
      { key: 1, val: 'test1' },
      { key: 2, val: 'test2' },
      { key: 3, val: 'test3' }
    ]
  });

testMethod() {
  this.testObservable()
    .pipe(
      pluck('Items'),
      map(items => items.filter(item => item.key != 2)),
      map(items => items.sort((a, b) => (a.key > b.key ? 1 : -1))),
      tap(items => { this.items$.next(items) })
    );

Answer №1

If you wanted to simplify the code, you could use:

this.testObservable()
  .pipe(
    map(value => 
        value.items.filter(item => item.key != 2)
             .sort((a, b) => (a.key > b.key ? 1 : -1))
    ),
    tap(this.items$.next)
  )

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

using props as arguments for graphql mutation in react applications

Here is the structure of my code: interface MutationProps{ username: any, Mutation: any } const UseCustomMutation: React.FC<MutationProps> = (props: MutationProps) => { const [myFunction, {data, error}] = useMutation(props.Mutati ...

Can you explain the contrast between Angular 2 components and directives?

I have been having difficulty grasping the distinction between these two ideas within the framework. I am quite experienced with directives in AngularJS 1.x, and both components and directives in Angular 2 appear to be closely related to this concept... ...

Encountering a 401 Unauthorized error while using the Post method with Angular 2 on the frontend and CakePHP 3 on the backend

Using Angular 2 for both the Front end and Back end within Cakephp 3, encountering a 401 Unauthorized status error during the login process. Although JWT has been configured in Cakephp 3 and works well in POSTMAN, it fails to work seamlessly with Angular. ...

Challenge with Typescript Interfaces

Can someone help me with understanding interfaces in typescript? I am currently facing an issue with the code. The error message says: Type 'Response' is missing the following properties from type 'myObj': userId, title, id I believe ...

Ensuring TypeORM thoroughly examines all columns with the decorators in NestJS

Is there a method to ensure the uniqueness validator in the TypeORM entity inspects all columns and provides notifications for all detected errors collectively? Consider this schema as an example: import { BaseEntity, Column, Entity, PrimaryGenera ...

Create a functioning implementation for retrieving a list of objects from a REST API

I am looking to incorporate an Angular example that retrieves a list from a REST API. Here is what I have attempted: SQL query: @Override public Iterable<Merchants> findAll() { String hql = "select e from " + Merchants.class.getName ...

What is preventing me from assigning to a class variable within a $http success handler?

During the course of my project, I have encountered a perplexing situation that is difficult to comprehend. My intuition tells me that the issue lies in a peculiar nuance of javascript while I am working in TypeScript. Unfortunately, I am unable to prove t ...

Curious Question: Can a class be created based on a specific prototype?

Imagine you have an existing schema definition object like this: const schema = { prop1: { type: String, maxLength: 8 }, prop2... }; Now, the challenge is to create a class that can generate documents using properties extracted from the schema without ha ...

When using an Angular2 application that relies on an external reference to Auth0Lock, the application encounters a NotFound error when executed

For my latest project, I decided to create an app using angular2-seed as a base. Everything was going smoothly until I tried deploying the production build on an Azure website. To my surprise, I encountered an issue when trying to load the page: > Refe ...

Is there a way to modify Font Awesome icon and text based on a specific condition?

component.html <i [title]="CardData.quantity > 1 || _ShippingVariable > 1 ? CannotShip : FreeShipping" [ngClass]="{'fa': true,'fa-youtube': socialMediaLink.socialMediaType === 'YOUTUBE',}"> ...

Is there a way to compile all TypeScript files within a C# project's .csproj file?

Scenario Every now and then, I find myself wanting to rebuild or recompile all TypeScript files in a typical VS 2017 .NET framework C# project (.csproj) without generating the dlls, and so on. I would greatly appreciate a simple console command solution f ...

Check to see whether the coordinates fall inside the specified bounding box

I am faced with the task of creating a function that can determine whether a given coordinate c lies within the boundaries of coordinates a and b. All variables in this scenario are of type: type Coordinate = { lat: number; lon: number; }; Initially ...

The Nest.js Inject decorator is not compatible with property-based injection

I am facing an issue with injecting a dependency into an exception filter. Here is the dependency in question: @Injectable() export class CustomService { constructor() {} async performAction() { console.log('Custom service action executed ...

Is there a way to determine if a route, or any of its nested routes, are currently active

Consider the following route examples: <Routes> <Route path="admin"> <Route path="users"> <Route index element={<UserList />} /> <Route path="create" element={<UserDetails ...

Adjust the component's input value using a different component

Let's talk about two components in this scenario - HomeComponent and UserComponent. The UserComponent is a child of the HomeComponent and has the following structure: UserComponent.html: <form [formGroup]="form"> <div style="display:block ...

Angular - optimizing performance with efficient HTTP response caching tactics

I'm managing numerous services that make requests to a REST service, and I'm looking for the optimal method to cache the data obtained from the server for future use. Can someone advise on the most effective way to store response data? ...

After subscribing, my Angular template fails to refresh

Currently, I am facing an issue with my Angular 17 project where the data fetched from the API is not updating the template. This means that despite receiving the data, I am unable to display it on the page. The code snippet below shows the service compon ...

Troubleshooting Problem with Angular 2 Filters

Here is an example of how I am utilizing the filter: <ion-item *ngFor="let contact of contacts | isMember"> <ion-label>{{contact.name}}</ion-label> {{contact.phoneNumber}}-{{contact.isMember}} </ion-ite ...

Evolution of Angular: Migrating from Angular 1 to Angular 5 with Nested Component

In the past Angular 1.5 ui-router Presently Angular 5.0 Is it possible to import subcomponents in a parent component similar to Angular 1.5? I followed the Heroes tutorial for Angular 5, but it did not cover this transition as all components are impo ...

The type is lacking the property onAuxClickCapture and onAuxClick

When utilizing forwardRef from React, an unexpected type error occurs: The type '{ children: ReactNode; }' is lacking the properties specified in 'Pick<ILinkProps, "className" | "children" | "accept" | "acceptCharset" | "action" | ... 34 ...