Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping objects by multiple columns with Lodash or Underscore

I have following object records:

 {  
   "notes":[  
      {  
         "id":1,
         "description":"hey",
         "userId":2,
         "replyToId":null,
         "postId":2,
         "parentId":null
      },
      {  
         "id":5,
         "description":"hey test",
         "userId":3,
         "replyToId":null,
         "postId":2,
         "parentId":null
      },
      {  
         "id":2,
         "description":"how are you",
         "userId":null,
         "replyToId":2,
         "postId":2,
         "parentId":null,
         "user":null
      }
   ]
}

I want to output it as:

2 
  object with id 1
  object with id 2 (because replyToId value is same as userId
3
  object with id 5

So basically I want to consider UserId and replyToId value under the same group.

I have build my own mixin under lodash, wrapping groupBy method as:

mixin({
    splitGroupBy: function(list, groupByIter){
        if (_.isArray(groupByIter)) {
            function groupBy(obj) {
                return _.forEach(groupByIter, function (key){
                    if ( !!obj[key] ) return obj[key]
                });

            }
        } else {
            var groupBy = groupByIter;
        }

        debugger;

        var groups = _.groupBy(list, groupBy);

        return groups;
    }
});

Call looks like this:

_.splitGroupBy(data.notes,['userId', 'replyToId']);

The output is coming without group. Even when I have tried with _.map instead _.forEach the split is not happening correctly.

like image 472
codebased Avatar asked Apr 12 '15 08:04

codebased


1 Answers

A solution using underscore:

    var props = ['userId', 'replyToId'];

    var notNull = _.negate(_.isNull);

    var groups = _.groupBy(record.notes, function(note){
        return _.find(_.pick(note, props), notNull);
    });
like image 59
Gruff Bunny Avatar answered Oct 20 '22 01:10

Gruff Bunny