按多个值分组Underscore.JS但保留键和值 [英] Group by multiple values Underscore.JS but keep the keys and values

查看:143
本文介绍了按多个值分组Underscore.JS但保留键和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用对象对以下数组进行分组:

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 } ]

正如你所看到它包含user_id和alert_id组合,其中我喜欢分组。所以我想拥有以下数组:

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]}]

任何人都知道解决方案吗?使用下划线的GroupBy,我可以根据一个键对值进行分组。但是我需要根据你可以看到的组合user_id AND alert_id对它们进行分组。

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.

我看了 underscore.nest ,但问题是它创建了自己的密钥。

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

推荐答案

groupBy 与使用user_id和alert_id创建复合键的函数一起使用。然后映射分组以获得您想要的内容:

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

这篇关于按多个值分组Underscore.JS但保留键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆