简体   繁体   中英

TypeScript get object nested in JSON

I have an object JSON:

"product": [
  {
    "code": "A",
    "value": "A",
    "id": 1,
    "subproduct": [
       { "name": "C", "id": 31 },
       { "name": "S", "id": 32 }
    ]
  }
]

I would like get the subproduct with the ID product The JSON is get by a service I try the code below:

let result = this.dataService.getJSON().pipe(
   map((x) => x.product),
   filter((y) => y.id === 1)
);

* UPDATE *

If i try the code, I have the code = "A"

this.dataService.getJSON().pipe(map((x) => x.product.filter((x) => x.id === 1)));

But It's doesn't work, Why I can't get the nested object "subproduct"

If i write

return this.dataService.getJSON().pipe(map((x) => x.product.subproduct.filter((x) => x.id === 1)));

I have this error

ERROR TypeError: "x.product.subproduct is undefined"

RESULT EXPECTED

below the result expected, I need just the subproduct

[
  { "name": "C", "id": 31 },
  { "name": "S", "id": 32 }
]

Thank for your help

Here is the solution. Hope it will work..

const product = [
      {
          "code": "A",
          "value": "A",
          "id": 1,
          "subproduct": [
               { "name": "C", "id": 31 },
               { "name": "S", "id": 32 }
          ]
      }
    ];
    const results = product.find(item => item.id === 1).subproduct;
    console.log(results);

When you pipe an Observable through filter operator - you are actually filtering the emissions of that Observable . To work with actual values that Observable emits - you need to put all the transformations inside the map operator.

let result = this.dataService.getJSON().pipe(
   map((data) => {
     return data.product.find((p) => p.id === your_id)
   }),
);

You have to define result observable stream with desired output and subscribe to it.

let result = this.dataService.getJSON().pipe(
  pluck('product'),
  map(products => {
    const product = products.find(eachProduct => eachProduct.id === 1);
    return product && product.subproduct;
  }),
);

Now you can subscribe to result observable to get subproduct array

result.subscribe(subproduct => {
  // You have access to subproduct array here.

  console.log(subproduct)
})

If product with id is not found, you'll get undefined subproduct in subscription assuming subproduct always exist for a given product.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM