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.
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.
Share Improve this question asked May 2, 2018 at 6:30 FrontEndDeveloperFrontEndDeveloper 991 gold badge2 silver badges11 bronze badges 3- You are getting only one object, you want to get the array of all the objects ? Is it what you mean ? – ibenjelloun Commented May 2, 2018 at 9:02
- Yes i want to get array of firstname and lastname seperately – FrontEndDeveloper Commented May 2, 2018 at 9:23
- is that worked for you ? – Pranay Rana Commented May 2, 2018 at 10:23
2 Answers
Reset to default 3You could simply use the arrays map function :
.pipe(
map(res => res.data),
map(a => ({
firstnames: a.map(_ => _.firstname),
lastnames: a.map(_ => _.lastname),
})),
);
Here is a running example.
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));