How do I groupBy on a HTTP response?

让人想犯罪 __ 提交于 2019-12-11 05:48:50

问题


I'm getting an array of objects as a HTTP response and I'm trying to group them by a value in the object. As an example let's say I get the following:

[
{player: 'Jordy Nelson', team: 'Packers'},
{player: 'Aaron Rogers', team: 'Packers'},
{player: 'Dak Prescott', team: 'Cowboys'},
{player: 'Ezekiel Elliot', team: 'Cowboys'},
{player: 'Joe Flacco', team: 'Ravens'},
{player: 'Julio Jones', team: 'Falcons'},
]

I'm trying to take that response and convert it to an array of objects, containing an array of objects

[
{'Packers': 
  [
    {player: 'Jordy Nelson', team: 'Packers'}, 
    {player: 'Aaron Rogers', team: 'Packers'}
  ]
},
{'Cowboys': 
  [
    {player: 'Dak Prescott', team: 'Cowboys'},
    {player: 'Ezekiel Elliot', team: 'Cowboys'}
  ]
},
{'Ravens':
  [
    {player: 'Joe Flacco', team: 'Ravens'}
  ]
},
{'Falcons':
  [
    {player: 'Julio Jones', team: 'Falcons'}
  ]
}
]

I've tried using groupBy in the way mentioned in other SO posts

return this.http
  .get(`${environment.baseUrl}/players`, options)
  .map(res => res.json())
  .groupBy(
    res => res.team,
    res => res // I've also tried removing this, filtering and flatmap
  )
  .flatMap(teams => {return teams})

But it returns a 2d array where axis 1 is a single object like so:

[
  [
    {'Packers': {player: 'Jordy Nelson', team: 'Packers'}
  ],
  [
    {'Packers': {player: 'Aaron Rogers', team: 'Packers'}
  ]
]

What do I need I to do format my response properly? Thanks!

With a lot of help from @coderek answer I wrote a little function that can dynamically regroup HTTP responses (so you don't hit the API for each time you'd like to groupBy on a different key). Here's the post on reddit if anyone else comes across this problem https://www.reddit.com/r/Angular2/comments/629nfg/how_to_dynamically_group_a_http_response/


回答1:


GroupBy works on streams. So First, you need to convert your source to stream first instead of array. Second, you get group results by stream, that's how observable works.

this.http.get('api/players')
  .mergeMap(a=> a.json().data)
  .groupBy(
      a=>a.team,
      a=>a,
  )
  .subscribe(
    (obs) =>{
        obs.subscribe((a)=>{
            console.log(a, obs.key);
        });
    }
  )
}


来源:https://stackoverflow.com/questions/43096470/how-do-i-groupby-on-a-http-response

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!