问题
sorry if this seems like a duplicate, but I've tried other answers and I can't seem to get something that works properly. I'm building an AngularJS SPA, and I have data in the following format:
"folders": [
{
"id": 1,
"password": "WPAUGOR452",
"year": 2013
},
{
"id": 2,
"password": "WPAUGOR452",
"year": 2013
},
{
"id": 3,
"password": "DFGOERJ305",
"year": 2014
}
and many many more.
I want folders to be grouped so that it's like this:
"folders": [
"2013": [
"WPAUGOR452": [
{
"id": 1,
"password": WPAUGOR452,
"year": 2013,
},
{
"id": 2,
"password": WPAUGOR452,
"year": 2013,
}
]
],
"2014": [
"DFGOERJ305": [
{
"id": 3,
"password": "DFGOERJ305",
"year": 2014
}
]
]
]
There is a lot more to the real data, but I've stripped it down to really what I want to group by. At present, every folder has a password and a year, and I want them to be grouped by password within years, so that I can display the year in the UI, and then all folders that are appropriate to a specific password.
Although please also note that I'll want to display the year and the password in the UI (only once, with the grouped items below!)
If any further detail is needed, please ask.
回答1:
This should do what you want:
var result = _.chain(folders)
.groupBy('year')
.mapObject( year => _.groupBy(year, 'password'))
.value();
And a version with a full function definition:
var result = _.chain(folders)
.groupBy('year')
.mapObject(function(year) {
return _.groupBy(year, 'password');
})
.value();
The solution first groups by year and then groups by password for each year group.
来源:https://stackoverflow.com/questions/38221432/grouping-a-nested-array-with-underscore-js