链lodash _.groupby()与降低
从类似的数组开始:
const arr = [
{id: "id_0", owner: "owner_0", state: "accepted"},
{id: "id_1", owner: "owner_1", state: "denied"},
{id: "id_2", owner: "owner_1", state: "accepted"},
{id: "id_3", owner: "owner_1", state: "accepted"},
{id: "id_4", owner: "owner_2", state: "pending"},
]
我需要按所有者对数据进行分组,然后格式化ID。 ID需要是逗号分隔的字符串。状态数据不必返回。
const formattedArr = {
owner_0: {ids: "id_0"},
owner_1: {ids: "id_1, id_2, id_3"}
owner_2: {ids: "id_4"}
}
我一直在使用_。groupby(arr,'所有者')
,但不确定如何使用回调或某些其他映射或简化以格式化ID并将它们加入字符串。
按照此方面的方式,但最好使用最少的循环:
_.chain(arr)
.groupBy('owner')
.reduce(group => {
//format the ids here
return *formatted ids*
}
.value()
Starting with an array similar to this:
const arr = [
{id: "id_0", owner: "owner_0", state: "accepted"},
{id: "id_1", owner: "owner_1", state: "denied"},
{id: "id_2", owner: "owner_1", state: "accepted"},
{id: "id_3", owner: "owner_1", state: "accepted"},
{id: "id_4", owner: "owner_2", state: "pending"},
]
I need to group the data by owner and format the ids. The ids need to be a comma separated string. The state data need not be returned.
const formattedArr = {
owner_0: {ids: "id_0"},
owner_1: {ids: "id_1, id_2, id_3"}
owner_2: {ids: "id_4"}
}
I've been using _.groupBy(arr, 'owner')
but not sure how to use a callback or some other map or reduce to format the ids and join them into a string.
Something along the lines of this but preferably using the least amount of loops:
_.chain(arr)
.groupBy('owner')
.reduce(group => {
//format the ids here
return *formatted ids*
}
.value()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因此,在这种情况下,您实际上不需要Groupby。减少可以轻松解决您的问题。
如果您喜欢Lodash,它看起来几乎相同。
祝你好运。
So, you actually don't need groupBy in this case. Reduce can easily solve your problem.
If you prefer lodash it would look almost the same.
Good luck.
这应该可以解决问题:
JS小提琴: https://jsfiddle.net/z3mks4n6/
This should do the trick:
JS Fiddle: https://jsfiddle.net/z3mks4n6/