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?
Highest voted answer uses Lodash
_.chain
function which is considered a bad practice now "Why using_.chain
is a mistake."Here is a fewliner that approaches the problem from functional programming perspective:
Where
input
is an array that you want to convert.I would suggest a different approach, using my own library you could do this in a few lines:
This would a be a bit difficult with lodash or Underscore because the arguments are in the opposite order order, so you'd have to use
_.partial
a lot.Example groupBy and sum of a column using Lodash 4.17.4
Thanks @thefourtheye, your code greatly helped. I created a generic function from your solution using the version 4.5.0 of Lodash.
To use it:
Here is the updated fiddler;
https://jsfiddle.net/sc2L9dby/
Isn't it this simple?
another way