sai123
sai123

Reputation: 105

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);
}

Upvotes: 0

Views: 529

Answers (3)

Durgesh Pal
Durgesh Pal

Reputation: 695

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);
      })
    );

Upvotes: 0

rafaelwalter
rafaelwalter

Reputation: 136

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);
      })

Upvotes: 1

Nithin Kumar Biliya
Nithin Kumar Biliya

Reputation: 3011

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);
      })

Upvotes: 0

Related Questions