I have a JSON response observable as below.I would like to get data from this observables in two seperate array such as [abc,xyz] and [aa,bb]. Is it possible using rx observables map and switchmap to get two arrays in the same observable.
this.data$ = Observable.of({
"data": [
{
"firstname": "abc",
"lastname": "aa"
},
{
"firstname": "xyz",
"lastname": "bb"
}
]
}) .map(res => res.data)
.switchMap(dataArray => {
return Observable.from(dataArray);
})
.map((arrayResp: any) => {
return ( arrayResp.firstname);
}).toArray()
Here iam only able to get one array. Is it possible to get two arrays in this method only.
You could simply use the arrays map function :
.pipe(map(res => res.data),
map(a => {
return {
firstnames: a.map(_ => _.firstname),
lastnames: a.map(_ => _.lastname)
}
}));
you have json string so you need to do like this in your switchMap
method
.switchMap(dataArray => {
return Observable.from(JSON.parse( dataArray));
})
or you can do like this also
this.data$ = Observable.of(JSON.parse(`{
"data": [
{
"firstname": "abc",
"lastname": "aa"
},
{
"firstname": "xyz",
"lastname": "bb"
}
]
}`).subscribe(res=> console.log(res.data));
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.