Grouping a nested array with underscore.js

十年热恋 提交于 2019-12-23 04:47:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!