最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - RxJs- Observable - How to fetch data from JSON Object - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 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.

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));
发布评论

评论列表(0)

  1. 暂无评论