使用 underscore.js 对嵌套数组进行分组 [英] Grouping a nested array with underscore.js

查看:46
本文介绍了使用 underscore.js 对嵌套数组进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉,如果这似乎是重复的,但我已经尝试了其他答案,但似乎无法得到正常工作的东西.我正在构建一个 AngularJS SPA,我有以下格式的数据:

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
  }

还有更多.

我希望对文件夹进行分组,如下所示:

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
      }
    ]
  ]
]

真实数据还有很多,但我已将其精简为真正我想要的分组依据.目前每个文件夹都有密码和年份,我希望它们在年份内按密码分组,这样我就可以在UI中显示年份,然后是所有适合特定密码的文件夹.

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.

尽管还请注意,我想在 UI 中显示年份和密码(仅显示一次,下面是分组的项目!)

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.

推荐答案

这应该可以满足您的需求:

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.

这篇关于使用 underscore.js 对嵌套数组进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆