2

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.

3
  • You are getting only one object, you want to get the array of all the objects ? Is it what you mean ? Commented May 2, 2018 at 9:02
  • Yes i want to get array of firstname and lastname seperately Commented May 2, 2018 at 9:23
  • is that worked for you ? Commented May 2, 2018 at 10:23

2 Answers 2

3

You 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.

Sign up to request clarification or add additional context in comments.

3 Comments

Can we not do this without the buffercount?
Sorry, I can't even understand why I ended up with something that complicated for this simple task. I edited my answer and also the stackblitz.
Thanks for the quick response!
2

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.