Refining the response object in Angular

I am trying to send a post request and want to filter the object response to extract specific data based on certain conditions. In my object response, I specifically need to find the object array for internet banking. After doing some research on Google, this is what I attempted:

response object:

{
  "header":
  {
    "serviceId":"xxx",
    "productCode":"xxx",
    "transactionId":"xxx"
  },
  "data":
  {
    "items":
    [
      {
        "paymentModel":"Retail Banking",
        "paymentChannels":
        [
          { "name":"A", "status":"Active" },
          { "name":"B", "status":"Active" },
          { "name":"C", "status":"Active" },
          { "name":"D", "status":"Active" }
        ],
        "name":"Internet Banking",
        "logoUrl":"xxx"
      },
      {
        "paymentModel":"Retail Banking",
        "paymentChannels":
        [
          {
            "bankFeeRate":"0",
            "ccIsRequired":true,
            "name":"R",
            "currency":
            [{
              "isoCode":"xxx",
              "name":"xxx"
            }],
            "bankFeeType":"xxx",
            "paymentChannelId":"9",
            "status":"Active",
            "acceptedCard":
            [
              "visa",
              "mastercard"
            ]
          },
          {
            "bankFeeRate":"0",
            "ccIsRequired":true,
            "name":"M",
            "currency":
            [{
              "isoCode":"xxx",
              "name":"xxx"
            }],
            "bankFeeType":"fixed",
            "paymentChannelId":"13",
            "status":"Active",
            "acceptedCard": [ "amex" ]
          }
        ],
        "name":"Credit Card",
        "logoUrl":"xxx"
      }
    ],
    "metadata": { "count":2 }
  },
  "status":
  {
    "code":"200",
    "message":"OK"
  }
}

component.ts

getPaymentChannel() {
  this.paymentService.getData(data)
  .pipe( map(
      res => res.filter(items => items.data.items ==='Internet Banking')
      .subscribe(res => console.log(res))
  ))
}

I would like to use *ngFor in HTML to display 'PaymentChannels[]', so I believe I need to filter this response by name, specifically credit card or internet banking. Here is the link to my StackBlitz demonstration demo. As I am new to rxjs and typescript, any guidance from experts would be highly appreciated.

Answer №1

If you are on the hunt for a single item, consider using the find method to return an object tailored to your needs. However, for this scenario, let's opt for filter instead.

It seems like your goal is to filter based on the name attribute within the items array. In that case, your filter should resemble something like this:

 map((res: PaymentModel) => 
   res.data.items.filter((x: Item) => x.name === 'Internet Banking')

If any matches are found, they will be presented in an array. To display the paymentChannels in the HTML, simply iterate through the array and use a nested ngFor loop to handle the paymentChannels:

<div *ngFor="let dat of myData">
  <div *ngFor="let p of dat.paymentChannels">
    <!-- ... -->
  </div>
</div>

Access Your Customized STACKBLITZ Here

You can achieve the same outcome using find as well: STACKBLITZ Link

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

How to set up an Angular animation using component input variables?

My goal is to introduce an @Input parameter that will define the timing of the animation in this demonstration of circle progress. However, the animation settings are currently specified within the @Component decorator, and it seems that this code does no ...

Create a pipeable stream that does not trigger any events when data is piped

I have been trying to utilize the renderToPipeableStream function from React18, and although it is functional, I am struggling with handling the pipe properly. The key section of my code involves an array of strings representing HTML. I am splitting the s ...

What is the purpose of adding "/dist" to the library import statement?

Currently, I am in the process of developing a react component library using vite as my primary build tool. After successfully compiling the project and deploying it to the npm registry, I encountered an issue when importing it into my client app. Specifi ...

Deleting a model from an array using Angular

I am working on a component that has a list of posts, and I retrieve them using the following code snippet: export class PostsComponent implements OnInit { posts; constructor(private http: Http) { } ngOnInit(): void() { this.http ...

The Angular material2 sidenav seems to be missing from the DOM, causing it not to show

I am facing an issue where the sidenav and header are separate components that share a service. It seems to be functioning properly as I can see the toggling action in the inspect element for the sidenav, but the actual sidenav is not displaying. https:// ...

Exploring the dynamic nature of pristine and dirty states in Dart Angular forms

In my application, I have a component that displays a user list and another component to show the details of a selected user. Much like the setup in the tutorial for hero list/detail components, when a user is selected from the list, it should become edita ...

AngularFire UPDATE -> APPLY CHANGES

I can't seem to figure this out. I'm wondering how to UPDATE a document that is returned in the WHERE clause using AngularFire: constructor(private db: AngularFirestore) { } var path = this.db.collection('users').doc('type') ...

The Angular ngFor directive is having trouble rendering data due to an issue with the bindings

I'm a beginner in Angular and despite reading multiple discussions, I haven't been able to find a solution to my problem. My frontend is displaying a blank page for my ngFor loop. Although the console shows that I am getting data from my API, I& ...

Can someone please provide instructions on dynamically adding bootstrao col-lg {n} based on the length of a record?

Here is the desired outcome: 1. If there is only one record, it should be displayed as "col-lg-12". 2. In the case of 2 records, they should be represented as "col-lg-6" & "col-lg-6". 3. For 3 records, use "col-lg-4" & "col-lg-4" & "col-lg-4 ...

Exploring the depths of a nested object by traversing through an array of its

Trying to iterate through a nested object structure with Angular TS: { "stringKey1": { "child": [ { "stringKey2": { "child": [] ...

Guide on integrating msw with Next.js version 13.2.1 (Issue: Unable to access worker.start on the server)

I'm currently in the process of integrating a simulated API that sends back a response object containing a series of messages meant to be displayed in the UI (specifically, a chatbox) alongside the username, user picture, and other relevant informatio ...

Ways to programmatically include routes with components sourced from a dynamically loaded module

One of my Angular components is dynamic and module-based: The module file is named dynamic-component.module.ts @NgModule({ imports: [ DynamicComponentRoutingModule, FormsModule, CommonModule, FormsModule, ], declarations: [ ...

Stop unauthorized access to a lazy-loaded module through direct routes

Within my application's structure, I utilize the MasterModule to load the MasterComponent along with its child routes. Among these child routes is one that lazy loads my EquipmentSLModule: master-routing.module.ts: const routes: Routes = [ { p ...

Improving the URL structure in Angular 8 with ngx-extended-pdf-viewer

How to prevent ngx-extended-pdf-viewer from removing # in Angular URL I have integrated "ngx-extended-pdf-viewer": "^7.3.2", and "zone.js": "~0.10.3" I need to retain the # in my URL: @NgModule({ imports: [RouterModule.forRoot(routes,{useHash: true,})] ...

Mapping Form Fields (with Formik)

Currently, the Formik/Yup validation setup in my form is working perfectly: export default function AddUserPage() { const [firstName, setFirstName] = useState(""); const [email, setEmail] = useState(""); return ( <div> <Formik ...

Create a separate helper function to extract browser logs using Protractor's afterEach

My main objective is to create a helper function that extracts the browser.manage().logs() data. I am working towards this goal by incorporating the functionality of browser.manage().logs() within the afterEach method in my test script. I have noticed tha ...

The concept of Nested TypeScript Map Value Type

Similar to Nested Typescript Map Type, this case involves nesting on the "value" side. Typescript Playground const mapObjectObject: Map<string, string | Map<string, string>> = new Map(Object.entries({ "a": "b", &quo ...

Creating a fresh addition to the primary menu in Jupyterlabs

I'm currently working on developing a plugin to introduce a fresh menu into the existing menu structure within Jupyterlabs interface.... next to file, edit, ... Settings, and Help The basic xkcd example is functioning correctly, and I've been th ...

Exploring the functionalities of bootstrapFactory with DartAngular 5

Here is a snippet of code showing the main method: Future<Null> main() async { final securityService = new SecurityService(new BrowserClient()); await securityService.getObject(); bootstrapStatic<AppComponent>( AppComponent, ...

Transform Promise-based code to use async/await

I'm attempting to rephrase this code using the async \ await syntax: public loadData(id: string): void { this.loadDataAsync() .then((data: any): void => { // Perform actions with data }) .catch((ex): v ...