angular - Angular observable,如何遍历具有嵌套数组的对象以将字段收集到数组中
问题描述
我正在尝试通过我的 JSON 对象并将特定字段添加到他们自己的数组中。
我正在尝试遍历下面的对象并将“appSupportedId”存储在它自己的数组中。
我收到一个错误
错误
core.js:15714 ERROR TypeError: info.flatMap is not a function
我在我的代码中实现了类似的东西,但与后端 json 对象的唯一区别是下面的对象有一个嵌套数组
任何帮助,将不胜感激!
组件.ts
userAppDetails:[];
this.incidentService.get(this.id)
.subscribe((info) =>
this.userAppDetails = (info.flatMap(x => x.applicationsSupported)).contactAll().map(y=> y.appSupportedId))
JSON对象
"incidentNumber": 18817,
"Email": null,
"applicationsSupported": [
{
"appSupportedId": 18569,
"supportAreaId": 122,
"supportAreas": {
"applicationId": 122,
"activeFlag": "Y",
},
"appSupportedName": "app 1"
},
{
"appSupportedId": 18592,
"supportAreaId": 123,
"supportAreas": {
"applicationId": 123,
"activeFlag": "Y",
},
"appSupportedName": "app 2"
},
{
"appSupportedId": 18655,
"supportAreaId": 122,
"supportAreas": {
"applicationId": 122,
"activeFlag": "Y",
},
"appSupportedName": "app 3"
}
],
"createdDate": "2020-01-17T18:02:51.000+0000",
解决方案
您似乎将可观察的管道运算符(在订阅前的管道内)与对象运算符(在订阅内)混合在一起。
RxJS 可管道操作符在可观察流中工作,它们非常强大。您甚至可以在订阅之前将一堆运算符放在一起。您有时可以在订阅中获得类似的结果,但这通常会导致代码混乱。
以下 ( https://stackblitz.com/edit/rxjs-d9nchy ) 是使用 map RxJS 运算符的示例。请注意,这与数组映射运算符不同:
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
const DATA = {
"incidentNumber": 18817,
"Email": null,
"applicationsSupported": [
{
"appSupportedId": 18569,
"supportAreaId": 122,
"supportAreas": {
"applicationId": 122,
"activeFlag": "Y",
},
"appSupportedName": "app 1"
},
{
"appSupportedId": 18592,
"supportAreaId": 123,
"supportAreas": {
"applicationId": 123,
"activeFlag": "Y",
},
"appSupportedName": "app 2"
},
{
"appSupportedId": 18655,
"supportAreaId": 122,
"supportAreas": {
"applicationId": 122,
"activeFlag": "Y",
},
"appSupportedName": "app 3"
}
],
"createdDate": "2020-01-17T18:02:51.000+0000",
}
const source = of(DATA).pipe(
map(x => x.applicationsSupported),
map(arr => arr.map(entry => entry.appSupportedId))
);
source.subscribe(x => console.log(x));