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

后端 未结 3 2051
日久生厌
日久生厌 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:21

    Use groupBy with a function that creates a composite key using user_id and alert_id. Then map across the groupings to get what you want:

        var list = [ { user_id: 301, alert_id: 199, deal_id: 32243 },
          { user_id: 301, alert_id: 200, deal_id: 32243 },
          { user_id: 301, alert_id: 200, deal_id: 107293 },
          { user_id: 301, alert_id: 200, deal_id: 277470 } ];
    
        var groups = _.groupBy(list, function(value){
            return value.user_id + '#' + value.alert_id;
        });
    
        var data = _.map(groups, function(group){
            return {
                user_id: group[0].user_id,
                alert_id: group[0].alert_id,
                deals: _.pluck(group, 'deal_id')
            }
        });
    

提交回复
热议问题