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)!