如何对HTTP响应进行分组? [英] How do I groupBy on a HTTP response?
问题描述
我正在将对象数组作为HTTP响应,并且尝试按对象中的值对它们进行分组.例如,假设我得到以下信息:
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'}
]
}
]
我已经尝试过其他SO帖子中提到的方式使用groupBy
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})
但是它返回2d数组,其中轴1是单个对象,如下所示:
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!
在@coderek答案的大量帮助下,我编写了一个小函数,可以动态地对HTTP响应进行重新分组(因此,每次希望对另一个键进行分组时,您都不会击中API).如果有人遇到此问题,请点击以下网址上的Reddit上的帖子 https://www.reddit.com/r/Angular2/comments/629nfg/how_to_dynamically_group_a_http_response/
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/
推荐答案
GroupBy
适用于流.所以首先,您需要将源转换为流而不是数组.其次,您可以按流获取组结果,这就是可观察的工作方式.
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);
});
}
)
}
这篇关于如何对HTTP响应进行分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!