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

Angular15: How can we properly provide support for legacy browsers?

I'm having issues with my Angular build on IOS12 as it's only displaying a blank page. Below are the dependencies listed in my package.json: "dependencies": { "@angular/animations": "^15.0.0", "@angular ...

Nebular specializes in crafting personalized registration solutions

I am currently working on a custom registration form that is different from the standard Nebular registration. Due to the custom form validation I have implemented, the standard registration system no longer functions as intended for me. I believe I need t ...

Utilizing Input Value from Parent Component in Angular TypeScript File: A Guide

Is there a way to manipulate the @Input()items in the child-component.ts file before passing it to child-component.html? Currently experiencing an issue where I get an empty object when logging in the ngOnInit method. child-component.ts @Input()items: ...

I keep encountering a syntax error every time I attempt to run the yarn start command

Upon attempting to execute yarn start, an error appeared in the command line indicating a syntax error. I have already attempted updates on both node and yarn. $ node --max_old_space_size=8192 ./node_modules/.bin/ng serve -H 0.0.0.0 --disable-host-check ...

Is it possible to globally define a namespace in Typescript?

Seeking a way to make my Input module accessible globally without the need for explicit path definitions. Currently, I have to import it like this: import { Input } from "./Input/Input";. Is there a method to simplify the import statement for modules con ...

TypeScript purity - "The variable exports is not defined"

I encountered an issue with my simple client-server TypeScript application where every import statement in my client.ts file triggers a ReferenceError: exports is not defined error in the browser after loading the HTML. Here is the project structure: root ...

Getter and Setter Implementation in Typescript without Using Classes

Check out these various SO questions discussing Typescript getters/setters: from 2015, Jan 2018, Sept 2018, and more. Now, the question arises - what is the best approach to define Typescript types for getters/setters in a plain JavaScript object without ...

learning how to transfer a value between two different components in React

I have 2 components. First: component.ts @Component({ selector: "ns-app", templateUrl: "app.component.html", }) export class AppComponent implements OnInit { myid: any; myappurl: any; constructor(private router: Router, private auth: ...

Top method for allowing non-component functions to update Redux state without the need to pass store.dispatch() as a parameter

As I work on my first ReactJS/redux project, I find myself in need of some assistance. I've developed a generic apiFetch<T>(method, params) : Promise<T> function located in api/apiClient.ts. (Although not a React component, it is indirect ...

Encountering an error in Angular 8 with the plugin: Unhandled ReferenceError for SystemJS

I recently followed a tutorial on integrating plugins into my Angular application at this link. I'm trying to create a component in my Angular app that can execute and display an external component. However, I encountered the following error: Uncaugh ...

Navigating with firebase authentication and angular routing

Currently, I am in the process of developing an ionic app using version 4. For this project, I have decided to utilize firestore as my database and implement firebase-authentication for user login and registration functionalities. However, I have encounter ...

Setting the default value for ngModel does not receive any information from the model

I am trying to populate a form with default values using the code below: <h3>ِStart Time</h3> <div class="row" > <div class="col"> <label for="startTime">Hour(s) </label> <input type="numb ...

Exploring the visitor design pattern with numerical enumerated types

I am exploring the use of the visitor pattern to ensure comprehensive handling when adding a new enum value. Here is an example of an enum: export enum ActionItemTypeEnum { AccountManager = 0, Affiliate = 4, } Currently, I have implemented the fol ...

Transform nested properties of an object into a new data type

I created a versatile function that recursively converts nested property values into numbers: type CastToNumber<T> = T extends string ? number : { [K in keyof T]: CastToNumber<T[K]> }; type StringMap = { [key: string]: any }; const castOb ...

Issue with Vue plugin syntax causing component not to load

I'm facing an issue with a Vue plugin that I have. The code for the plugin is as follows: import _Vue from "vue"; import particles from "./Particles.vue"; const VueParticles = (Vue: typeof _Vue, options: unknown) => { _Vue. ...

Issue: React child components cannot be objects (received: object with keys)

Hey everyone, I could really use some help figuring out what I'm doing wrong. Here is the error message I'm receiving: Error: Objects are not valid as a React child (found: object with keys {id, title, bodyText, icon}). If you meant to render a ...

The name 'BrowseAnimationModule' cannot be located

Can someone help me figure out how to install or fix this import issue I'm having with the 'animations' directory in @angular/platform-browser/animations not importing properly? import {CommonModule} from '@angular/common'; import ...

The type 'undefined' cannot be assigned to type 'Element or null'

One of the components I am using looks like this: const data: any[] = [] <Tiers data={data}/> This is how my component is structured: const Tiers = ({ data, }: { data?: any; }) => { console.log('data', data?.length!); ...

Custom type checker that validates whether all properties of a generic object are not null or undefined

In an attempt to create a user-defined type guard function for a specific use-case, I am faced with a challenge: There are over 100 TypeScript functions, each requiring an options object. These functions utilize only certain properties from the object wh ...

What are the best practices for styling a component in Fluent UI when using React and TypeScript?

I'm attempting to set a background color for this specific div element: import * as React from 'react' import { Itest } from '../../../../../models' import { getPreviewStyles } from './preview.style.ts' type IPreviewP ...