Underscore.js groupBy multiple values

前端 未结 9 1439
渐次进展
渐次进展 2020-12-01 05:03

Using Underscore.js, I\'m trying to group a list of items multiple times, ie

Group by SIZE then for each SIZE, group by CATEGORY...

http://jsfiddle.net/ricky

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 05:13

    The improvements by joyrexus on bergi's method don't take advantage of the underscore/lodash mixin system. Here it is as a mixin:

    _.mixin({
      nest: function (collection, keys) {
        if (!keys.length) {
          return collection;
        } else {
          return _(collection).groupBy(keys[0]).mapValues(function(values) {
            return _.nest(values, keys.slice(1));
          }).value();
        }
      }
    });
    

提交回复
热议问题