Group by multiple values Underscore.JS but keep the keys and values

后端 未结 3 2019
日久生厌
日久生厌 2020-12-01 12:19

I\'m trying to group the following array with objects:

[ { user_id: 301, alert_id: 199, deal_id: 32243 },
  { user_id: 301, alert_id: 200, deal_id: 32243 },
         


        
3条回答
  •  独厮守ぢ
    2020-12-01 12:24

    I would like to contribute a neat typescript ES6 group by.
    I am not really sure how to tighten up the return value typing. Some trickery is needed there, but this works rather well for me.

    /**
     * group the supplied list by a set of keys.
     * @param list the list of items to group.
     * @param children the key for the array of child items.
     * @param components the components to group by.
     */
    groupByMultipleFields(
        list: T[],
        children: string,
        ...components: K[]): any[] {
    
        var grouping = [...list.reduce((r, o) => {
            const key = components.map(_ => `${o[_]}`).join(" :: ");
            var keyed = r.get(key) || components.reduce((x, y) => { x[y] = o[y]; return x; }, {});
            keyed[children] = keyed[children] || [];
            keyed[children].push(o);
            return r.set(key, keyed);
        }, new Map).values()];
        return grouping;
    
    }
    

    You will need to turn on the typescript compiler option "downlevelIteration": true to allow the new Map to iterate and return values().

提交回复
热议问题