Grouping an array by postId and userId I've got this kind of data:

[
  { userId: 1, postId: 1, ... },
  { userId: 1, postId: 2, ... },
  { userId: 2, postId: 3, ... },
  ...
]


And I need to group them by postId and userId like this:

{
  1: { 1: [{ ... }], 2: [{ ... }], ...},
  2: { 3: [{ ... }], ...},
  ...
}


Here is what I've done so far:

var posts = {};
_.forEach(response.posts, function (post) {
    if (!posts[post.userId]) {
        posts[post.userId] = {};
    }
    if (!posts[post.userId][post.postId]) {
        posts[post.userId][post.postId] = [];
    }

    posts[post.userId][post.postId].push(post);
});


Any suggestion is welcome (a functional way of doing it using lodash would be great)!
As you noted, a more functional solution could be better.  Here is a way to write it using lodash.js:

var data = [
             { userId: 1, postId: 1, postData: "first post first user" },
             { userId: 1, postId: 2, postData: "second post first user" },
             { userId: 2, postId: 3, postData: "first post second user" }
           ];

posts = _
  .chain(data)
  .groupBy('userId')
  .mapValues(function(x) {
    return _.extend.apply(this, _.map(x, function (y) {
      return {[y.postId]: y.postData };
    }));
  })
  .value();


The .groupBy('userId') makes the intention clearer, but whether it is a better solution than the original is debatable.  Therefore, you may be better off leaving the code as it is.