Struggling with a problem involving RXJS transformation in an Ionic 2 application. My goal is to flatten a JSON file into objects, here is the simplified JSON structure:
[{
"language": "it",
"labels": {
"name": "Hi",
},
"types": [
{"name": "test 1"},
{"name": "test 2"}
]
},...]
This is the TypeScript code snippet:
export class MyRecord{
name: string;
label_name: string;
constructor(name: string, label_name: string) {
this.name = name;
this.label_name = label_name;
}
}
public getRecords() {
var url = '../assets/records.json';
let records$ = this.http
.get(url)
.map(mapRecords);
return records$;
function mapRecords(response: Response): MyRecord[] {
return response.json().filter(x => x.language == "it")
.map(({ language, labels, types }) => types.map(type =>
toMyRecord(labels, type))
);
}
function toMyRecord(l: any, t: any): MyRecord{
let record= new MyRecord(
t.name,
l.name,
);
return record;
}
When I make a call to the service:
members: MyRecord[];
this.myService.getRecords().subscribe(res => {
this.members = res;
},
err => console.log(err)
);
The issue lies in this.members being an array of arrays of MyRecord:
[[{ label_name: "Hi", name: "test 1"}, { label_name: "Hi", name: "test 2"} ]]
instead of just an array of MyRecord:
[{ label_name: "Hi", name: "test 1"}, { label_name: "Hi", name: "test 2"} ]
I attempted to use flatMap (mergeMap), but encountered the error 'flatMap is not a function' (even though I imported the mergeMap operator). Also, questioning how this.members defined as an array of MyRecord can accept a different type.