0

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 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This worked like a charm! I would just like to say that Visual Studio 2013 is saying there's a syntax error with the > symbol in the =>. The JavaScript DOES run though, any ideas on why this could be? Thanks a lot!
It turns out that => doesn't work in IE 10. Is there an alternative syntax I can use?
Perfect! The full function method works! I did try and modify the code to work with a function but I was doing something really stupid. Thanks for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.