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

时间:2015-04-12 08:31:21

标签: 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
      }
   ]
}

我想将其输出为:

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

所以基本上我想在同一组下考虑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;
    }
});

通话看起来像这样:

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

输出没有组。即使我尝试使用_.map代替_.forEach,分割也没有正确发生。

5 个答案:

答案 0 :(得分:8)

使用下划线的解决方案:

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

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

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

答案 1 :(得分:1)

这可能做得更漂亮,但它应该有效:

lodash.mixin({
  splitGroupBy: function(list, groupByIter) {
    var _ = this, groupBy;
    if (lodash.isArray(groupByIter)) {
      groupBy = function(obj) {
        return _(obj) .pick(groupByIter)
                      .values()
                      .without(null, undefined)
                      .first();
      };
    } else {
      groupBy = groupByIter;
    }
    var groups = _.groupBy(list, groupBy);
    return groups;
  }
});

答案 2 :(得分:1)

您可以将属性列表映射到各自的值,然后选择第一个非虚假值作为组密钥:

_.mixin({
    splitGroupBy: function(list, groupByIter){
        if (!_.isArray(groupByIter))
            return _.groupBy(list, groupByIter);

        return _.groupBy(list, function(o) {
            var values = _.map(groupByIter, function(k) {
                return o[k];
            });
            return _.find(values);
        });
    }
});

var data = {  
   "notes":[  
      {  
         "id":1,
         "userId":2,
         "replyToId":null
      },
      {  
         "id":5,
         "userId":3,
         "replyToId":null
      },
      {  
         "id":2,
         "userId":null,
         "replyToId":2
      }
   ]
};

_.mixin({
    splitGroupBy: function(list, groupByIter){
        if (!_.isArray(groupByIter))
            return _.groupBy(list, groupByIter);

        return _.groupBy(list, function(o) {
            var values = _.map(groupByIter, function(k) {
                return o[k];
            });
            return _.find(values);
        });
    }
});

snippet.log(JSON.stringify(_.splitGroupBy(data.notes,['userId', 'replyToId'])));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

答案 3 :(得分:1)

假设userIdreplyToId是相互排斥的(即您有userIdreplyToId,但从不两者都有),因为它们在示例数据中,指定自定义分组功能有效:

_.groupBy(data.notes, function(note) {
    return note.userId || note.replyToId;
});

答案 4 :(得分:1)

您可以将stringify对象用作键。

_.groupBy(notes, ({ userId, replyToId }) => JSON.stringify({ userId, replyToId }));

输出:

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