使用Lodash或Underscore按多列分组对象 [英] Grouping objects by multiple columns with Lodash or Underscore

查看:421
本文介绍了使用Lodash或Underscore按多列分组对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下对象记录

 {  
   "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
      }
   ]
}

我想将其输出为:

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



<那么基本上我想考虑同一组下的UserId和replyToId值。

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

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

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;
    }
});

电话看起来像这样:

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

输出没有组。即使我尝试使用 _。map 而不是 _。forEach ,拆分也没有正确进行。

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

推荐答案

使用下划线的解决方案:

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);
    });

这篇关于使用Lodash或Underscore按多列分组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆