Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

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

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 },
  { user_id: 301, alert_id: 200, deal_id: 107293 },
  { user_id: 301, alert_id: 200, deal_id: 277470 } ]

As you can see it contains user_id and alert_id combinations, which I like to group. So I would like to have the following array:

[ { user_id: 301, alert_id: 199, deals: [32243] },
  { user_id: 301, alert_id: 200, deals: [32243,107293,277470]}]

Anyone knows a solution for this? With underscore's GroupBy I can group the values based on one key. But I need to group them, based on the combination user_id AND alert_id, as you can see.

I took a look at underscore.nest, but the problem is it creates its own keys.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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')
        }
    });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...