使用Lodash或Underscore按多列分组对象

cod*_*sed 8 javascript underscore.js lodash

我有以下对象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
      }
   ]
}
Run Code Online (Sandbox Code Playgroud)

我想将其输出为:

2 
  object with id 1
  object with id 2 (because replyToId value is same as userId
3
  object with id 5
Run Code Online (Sandbox Code Playgroud)

所以基本上我想在同一组下考虑UserId和replyToId值.

我在lodash下构建了自己的mixin,将groupBy方法包装为:

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;
    }
});
Run Code Online (Sandbox Code Playgroud)

电话看起来像这样:

_.splitGroupBy(data.notes,['userId', 'replyToId']);
Run Code Online (Sandbox Code Playgroud)

输出没有组.甚至当我试图用_.map,而不是_.forEach分裂没有正确发生.

Gru*_*nny 9

使用下划线的解决方案:

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

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

    var groups = _.groupBy(record.notes, function(note){
        return _.find(_.pick(note, props), notNull);
    });
Run Code Online (Sandbox Code Playgroud)