Handling JSON data with Reactive Extensions in JavaScript

Hey everyone, I'm a beginner in Angular and RxJS coming from a background in VueJS. I've been struggling to grasp the inner workings of RxJS and would really benefit from some guidance from more experienced individuals regarding my current issue.

What I aim to achieve: I am using the nomics API(see link below) to fetch data which is returned as an array of objects. While I know how to easily display all objects on my component, I'm facing a challenge when it comes to selecting a specific object based on one of its properties. For instance, "loop through each object in the array until I find the object where object.Currency == 'BTC' ". Currently, I am able to retrieve all data and display it successfully. Can anyone show me how to filter the data based on a condition related to one of the objects?

API Link:

My code:

getDashboard() {
return this.http.get(`${this.apiUrl}/dashboard?key=${this.apiKey}`).pipe(
  map(result => {
    console.log(result);
    // Here I need help to extract the object with a specific property in Object.Currency
    // For example, iterate through objects until currentObject.Currency== 'Some string'
  })
)

}

Answer №1

If you have an array of objects, one way to filter them is by using the filter() array operator.

 this.http.get(`${this.apiUrl}/dashboard?key=${this.apiKey}`).pipe(
      tap(console.log),
      map(arr=>arr.filter(obj => obj.Currency && obj.Currency == 'BTC' ))
    )

Alternatively, you can also achieve the same result with the following approach:

 this.http.get(`${this.apiUrl}/dashboard?key=${this.apiKey}`).pipe(
      tap(console.log),
      switchMap(arr=>from(arr)),
      filter(obj => obj.Currency && obj.Currency == 'BTC' ),
      toArray()
    )

Answer №2

Make sure to add the filter to your response in the following way:

  fetchResults() {
    return this.http.get(`${this.apiUrl}/results?key=${this.apiKey}`).pipe(
      map(response => response.pipe(filter(item => item.Status == 'Some status')))
    )
  }

Consider applying this filtering logic in your component where you handle the response data, rather than in the service that sends the API request.

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

Definition file for mapbox-gl-draw in Typescript, also known as d.ts file

I attempted to define the mapbox-gl-draw project in a typed manner but unfortunately, I was unsuccessful. Can anyone provide some guidance on this? Here is how the javascript file looks: 'use strict'; var Setup = require('./src/setup&apos ...

Is there a missing .fillGeometry in the Figma plugin VectorNode?

The documentation for VectorNode mentions a property called fillGeometry. Contrary to this, TypeScript indicates that "property 'fillGeometry' does not exist on type 'VectorNode'". I seem to be missing something here. Can someone prov ...

What is the process for obtaining a flattened tuple type from a tuple comprised of nested tuples?

Suppose I have a tuple comprised of additional tuples: type Data = [[3,5,7], [4,9], [0,1,10,9]]; I am looking to develop a utility type called Merge<T> in such a way that Merge<Data> outputs: type MergedData = Merge<Data>; // type Merged ...

Error: It is not possible to assign a value to the Request property of the Object since it only has a getter method

Encountering issues while attempting to deploy my Typescript Next.js application on Vercel. The build process fails despite functioning correctly and building without errors locally. Uncertain about the root cause of the error or how to resolve it. The f ...

Utilizing multiple page objects within a single method in Cypress JS

I have been grappling with the concept of utilizing multiple page objects within a single method. I haven't been able to come up with a suitable approach for implementing this logic. For instance, consider the following methods in my page object named ...

What is the proper way to add an SSL cert to an Angular HTTP API request?

Is there a need to utilize a certificate when making an API call to retrieve an access token? For example, if the method is POST at getAccess.com/getCode, how should we handle this in Postman with a certificate attached? I am currently working on an Angula ...

typescript undefined subscription to observable

After making an http request to fetch some data, I am facing issues in displaying it as intended. The dropdown select for entriesPerPage, and the left and right cursors for switching page in pagination are working fine. However, upon switching a page, I en ...

Unusual Outcome from Observable.interval() Combined with flatMap()

When attempting to chain Observable.interval() with .flatMap(), I encountered what seems to be unexpected behavior. Below is the code snippet I am using (with Angular 2): Observable.interval(1500) .scan((numArr:any[], curr:any, i:number) => { nu ...

Encountering an error in a map operation does not hinder the subsequent map operation from being carried out

Within my angular application, I have implemented a Login method that performs the following tasks: login(username, password): Observable<User> { let data = new URLSearchParams(); data.append('username', username); data.append(' ...

Creating a sleek navigation bar and sliding feature within the header of your Ionic 2

I am looking to create a sliding header for my website where the gallery hides and the navbar moves to the top as I scroll down, similar to the gif provided. Any help or ideas on how to achieve this would be greatly appreciated. Thank you. https://i.sstat ...

Is the Scope Staying Static in AngularJS 1.4 when Input Text Changes and Two-Way Binding is Enabled?

Encountering a strange issue with AngularJS 1.4 (TypeScript). The problem lies within the controller where a variable is set and displayed in an input text box. Oddly, when attempting to edit the value in this text box and clicking on a button, the variabl ...

Tips on how to effectively unit test error scenarios when creating a DOM element using Angular

I designed a feature to insert a canonical tag. Here is the code for the feature: createLinkForCanonicalURL(tagData) { try { if (!tagData) { return; } const link: HTMLLinkElement = this.dom.createElement('link'); ...

Angular 5: Unable to add a destroyed View to a ViewContainer

I encountered a new error in my Angular application that I haven't seen before. The issue is arising from this specific line in the Angular source code. This error occurs when I log out and then log back into my app. While on a certain route, there i ...

Leveraging Angular, ExpressJS, and NodeJS to enable users to download a text file by simply clicking a

My goal is to incorporate a download button that allows users to download a document from my node.js server. Behold the stylish download button: https://i.sstatic.net/s4CjS.png My tech stack includes Angular for the front-end and node.js along with exp ...

Removing buttons from a table row dynamically

Below is how I am adding the Button to Element: (this.sample as any).element.addEventListener("mouseover", function (e) { if ((e.target as HTMLElement).classList.contains("e-rowcell")) { let ele: Element = e.target as Element; let ro ...

Navigating with Tabs in Ionic Angular is a Breeze

Here is the routing configuration found in app-routing.module: const routes: Routes = [ { path: 'displayfile/:navitemid', loadChildren: () => import('./pages/file-viewer/file-viewer.module').then( m => m.FileViewerPageMo ...

Versatile Typescript options

Is it possible to enforce a value to be within a list using TypeScript with enums? Can this be achieved with TypeScript type definitions? enum Friend { JOHN, SALLY, PAUL, } type MyFriends = { friends: Friend[], bestFriend: <> //How ca ...

Mobile devices experiencing navigation bar toggle issue

I've created this code for the navigation bar, but I'm having an issue with the hamburger icon not working on small devices. The icon is visible, but nothing happens when I try to click it. <nav class="navbar navbar-expand-lg navbar-dark ...

Can you retrieve the form control names in an array within an Angular reactive form?

<div *ngFor="let response of responsesForm?.get('responses')?.value; let i = index;"> <div [innerHTML]="response.content"></div> <textarea formControlName="response.content"></texta ...

Ways to turn off Typescript alerts for return statements

I'm looking to turn off this Typescript warning, as I'm developing scripts that might include return values outside of a function body: https://i.stack.imgur.com/beEyl.png For a better example, check out my github gist The compiled script will ...