Filter observable's subscription response for nested child array object

I am subscribing to the observable which gives me the below Object

{
  "Make" : "Make123",
  "Model":
  {
    "Type": "a12",
    "Items": [
      {"id": 1, "Location": "xyz"},
      {"id": 2, "Location": "abc"},
      {"id": 3, "Location": "def"}
    ]
  }
}

I want to filter to get the items array with id=3 and assign to a variable named actualItem.

I have tried to do it, but failed.

item.ts

export interface Items {
  id: number;
  Location: number;
}        

model-data.component.ts

import { Items } from '../item.ts';
actualItem: Items;

getItem() {
  this.actualItem = this.ModelData$.subscribe(modelData => {
    return modelData.Model.Items
      .filter(item => item.id == 3);
  })

  console.log(this.actualItem);
}

3 answers

  • answered 2019-09-15 17:27 Nithin Kumar Biliya

    subscribe returns a subscription object which you can use to unsubscribe from it. It is not the returned object from the subscription success callback function.

    This is the code you need to assign the filtered item to the actualItem variable -

          this.ModelData$.subscribe(modelData => {
            this.actualItem = modelData.Model.Items
            .filter(item => item.id == 2);
          })
    

  • answered 2019-09-15 17:30 rafaelwalter

    Subscribe returns a subscription.

    To access the data you have subscribed into you must pass in a callback to handle the success event. The data will only be accessible within the callback.

    I believe this.actualItem is an object rather than an array, so I changed the method filter to find which actually returns the element and quits the searching once it has been found.

         this.ModelData$.subscribe(modelData => {
            this.actualItem =  modelData.Model.Items.find(item => item.id == 2);
          })
    
    

  • answered 2019-09-15 18:27 Durgesh Pal

    Even you don't need to subscribe the observable. Use tap to get the Item {}

    this.ModelData$.pipe(
          tap(data => {
            this.actualItem = data.Model.Items.find(item => item.id == 2);
          })
        );