使用underscore.js对嵌套数组进行分组

时间:2016-07-06 10:10:11

标签: javascript underscore.js

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

"folders": [
  {
    "id": 1,
    "password": "WPAUGOR452",
    "year": 2013
  },
  {        
    "id": 2,
    "password": "WPAUGOR452",
    "year": 2013
  },
  {        
    "id": 3,
    "password": "DFGOERJ305",
    "year": 2014
  }

还有很多。

我想要对文件夹进行分组,使其像这样:

"folders": [
  "2013": [
    "WPAUGOR452": [
      {
        "id": 1,
        "password": WPAUGOR452,
        "year": 2013,
      },
      {
        "id": 2,
        "password": WPAUGOR452,
        "year": 2013,
      }             
    ]
  ],
  "2014": [
    "DFGOERJ305": [
      {        
        "id": 3,
        "password": "DFGOERJ305",
        "year": 2014
      }
    ]
  ]
]

真实数据还有很多,但我已经把它剥离到了我想要分组的地步。目前,每个文件夹都有一个密码和一年,我希望它们可以在几年内按密码分组,这样我就可以在UI中显示年份,然后显示适合特定密码的所有文件夹。

虽然请注意我还想在UI中显示年份和密码(只有一次,下面是分组项目!)

如果需要进一步的细节,请询问。

1 个答案:

答案 0 :(得分:3)

这应该做你想要的:

class MyExclusionStrategy implements ExclusionStrategy {
Set<String> encounteredClasses = new HashSet<String>();

public boolean shouldSkipField(FieldAttributes fa) {
    return false;
}

@Override
public boolean shouldSkipClass(Class<?> type) {
    System.out.println(encounteredClasses);
    if (encounteredClasses.contains(type.getSimpleName().toString())) {
        return true;
    } if (type.isAnnotationPresent(Entity.class)) {
        encounteredClasses.add(type.getSimpleName().toString());
    }
    return false;
}}

具有完整功能定义的版本:

@RequestMapping(method = RequestMethod.POST, value = "/windparks/import/error")
public ModelAndView handleFileUploadError(Locale locale, @AuthenticationPrincipal SpringUser authenticatedUser, List<RegulationEvent> regList, @RequestParam("regulations") MultipartFile regulations, RedirectAttributes redirectAttributes, @PathVariable String windparkId) throws IOException, WindSpeedInterpolator.TimeSeriesMismatchException, SAXException {
    ModelAndView view = new ModelAndView("uis/windparks/parkdetail");

    view.addObject("failedEvents", regList);
    view.addObject("windparkId", windparkId);


    return view;
}

@RequestMapping(method = RequestMethod.POST, value = "/windparks/import/error")
public ModelAndView handleFileUploadError(Locale locale, @AuthenticationPrincipal SpringUser authenticatedUser, RedirectAttributes redirectAttributes, @PathVariable String windparkId) throws IOException, WindSpeedInterpolator.TimeSeriesMismatchException, SAXException {
    ModelAndView view = new ModelAndView("uis/windparks/parkdetail");

    view.addObject("windparkId", windparkId);


    return view;
}

解决方案首先按年份分组,然后按年份分组密码。