[英]TypeScript get object nested in JSON
我有一个 object JSON:
"product": [
{
"code": "A",
"value": "A",
"id": 1,
"subproduct": [
{ "name": "C", "id": 31 },
{ "name": "S", "id": 32 }
]
}
]
我想获得 ID 为产品的子产品 JSON 是通过服务获得的,我尝试以下代码:
let result = this.dataService.getJSON().pipe(
map((x) => x.product),
filter((y) => y.id === 1)
);
* 更新 *
如果我尝试代码,我有代码 =“A”
this.dataService.getJSON().pipe(map((x) => x.product.filter((x) => x.id === 1)));
但它不起作用,为什么我不能得到嵌套的 object “子产品”
如果我写
return this.dataService.getJSON().pipe(map((x) => x.product.subproduct.filter((x) => x.id === 1)));
我有这个错误
ERROR TypeError: "x.product.subproduct is undefined"
预期结果
低于预期的结果,我只需要子产品
[
{ "name": "C", "id": 31 },
{ "name": "S", "id": 32 }
]
感谢您的帮助
这是解决方案。 希望它会工作..
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);
当您 pipe 是Observable
通过filter
运算符时-您实际上是在过滤该Observable
的排放。 要使用Observable
发出的实际值 - 您需要将所有转换放在map
运算符中。
let result = this.dataService.getJSON().pipe(
map((data) => {
return data.product.find((p) => p.id === your_id)
}),
);
您必须使用所需的 output 定义result
可观察 stream 并订阅它。
let result = this.dataService.getJSON().pipe(
pluck('product'),
map(products => {
const product = products.find(eachProduct => eachProduct.id === 1);
return product && product.subproduct;
}),
);
现在您可以订阅result
observable 以获取subproduct
数组
result.subscribe(subproduct => {
// You have access to subproduct array here.
console.log(subproduct)
})
如果未找到具有id
的产品,您将在订阅中获得undefined
的子产品,假设子产品始终存在于给定产品中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.