我有从 API 返回的示例数据。
我正在使用 Lodash 的 _.groupBy
将数据转换为我可以更好地使用的对象。
返回的原始数据是这样的:
[
{
"name": "jim",
"color": "blue",
"age": "22"
},
{
"name": "Sam",
"color": "blue",
"age": "33"
},
{
"name": "eddie",
"color": "green",
"age": "77"
}
]
我希望 _.groupBy
函数返回一个如下所示的对象:
[
{
color: "blue",
users: [
{
"name": "jim",
"color": "blue",
"age": "22"
},
{
"name": "Sam",
"color": "blue",
"age": "33"
}
]
},
{
color: "green",
users: [
{
"name": "eddie",
"color": "green",
"age": "77"
}
]
}
]
目前我正在使用
_.groupBy(a, function(b) { return b.color})
这是返回这个。
{blue: [{..}], green: [{...}]}
分组是正确的,但我真的很想添加我想要的键( color
, users
)。这可以使用 _.groupBy
吗?或其他一些 LoDash
实用程序?
原文由 user1767105 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以在 Underscore 和 Lodash(3.x 和 4.x)中这样做。
原始答案
在线演示
注意: 从 Lodash 4.0 开始,
.pairs
函数已重命名为_.toPairs()