Underscore.js groupBy multiple values

前端 未结 9 1492
渐次进展
渐次进展 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:21

    Grouping by a composite key tends to work better for me in most situations:

    const groups = _.groupByComposite(myList, ['size', 'category']);
    

    Demo using OP's fiddle

    Mixin

    _.mixin({
      /*
       * @groupByComposite
       *
       * Groups an array of objects by multiple properties. Uses _.groupBy under the covers,
       * to group by a composite key, generated from the list of provided keys.
       *
       * @param {Object[]} collection - the array of objects.
       * @param {string[]} keys - one or more property names to group by.
       * @param {string} [delimiter=-] - a delimiter used in the creation of the composite key.
       *
       * @returns {Object} - the composed aggregate object.
       */
      groupByComposite: (collection, keys, delimiter = '-') =>
        _.groupBy(collection, (item) => {
          const compositeKey = [];
          _.each(keys, key => compositeKey.push(item[key]));
          return compositeKey.join(delimiter);
        }),
    });
    

提交回复
热议问题