I have this sample data returned from an API.
I'm using Lodash's _.groupBy
to convert the data into an object I can use better.
The raw data returned is this:
[
{
"name": "jim",
"color": "blue",
"age": "22"
},
{
"name": "Sam",
"color": "blue",
"age": "33"
},
{
"name": "eddie",
"color": "green",
"age": "77"
}
]
I want the _.groupBy
function to return an object that looks like this:
[
{
color: "blue",
users: [
{
"name": "jim",
"color": "blue",
"age": "22"
},
{
"name": "Sam",
"color": "blue",
"age": "33"
}
]
},
{
color: "green",
users: [
{
"name": "eddie",
"color": "green",
"age": "77"
}
]
}
]
Currently I'm using
_.groupBy(a, function(b) { return b.color})
which is returning this.
{blue: [{..}], green: [{...}]}
the groupings are correct, but I'd really like to add the keys I want (color
, users
). is this possible using _.groupBy
? or some other LoDash
utility?
You can do it like this
Online Demo
Note: Lodash 4.0 onwards, the
.pairs
function has been renamed to_.toPairs()
Here is an updated version using lodash 4 and ES6
In 2017 do so