Underscore.js 个 属性 的唯一值和计数:连同另一个 属性。:2 个级别
Underscore.js unique values and counts of a property : alongwith another property.: 2 levels
我是 Underscore.js
的新手
假设我有这个对象数组:
[
{ couponid: 500, locationid: 10 },
{ couponid: 600, locationid: 15 },
{ couponid: 500, locationid: 10 },
{ couponid: 500, locationid: 20 }
]
我得到了独特的优惠券 (500,600) 以及每个优惠券的计数,使用:
_.countBy(result, "couponid")
其中result为数组
谁能告诉我,现在我怎样才能为每个唯一的优惠券 ID 获得多少个唯一的位置 ID(连同位置 ID)?即在上面的 couponid 500 将计数 2,而 couponid 600 将计数 1.
如果我理解正确的话,我想这会做你想做的事:
var result = _.chain(data)
.groupBy('couponid')
.mapObject( group => _.countBy(group, 'locationid'))
.value()
首先我们按 couponid
分组,然后映射该对象以计算该组中的每个 locationid
。
这将生成如下所示的对象:
{
500: {
10: 2,
20: 1
},
600: {
15: 1
}
}
我是 Underscore.js
的新手假设我有这个对象数组:
[
{ couponid: 500, locationid: 10 },
{ couponid: 600, locationid: 15 },
{ couponid: 500, locationid: 10 },
{ couponid: 500, locationid: 20 }
]
我得到了独特的优惠券 (500,600) 以及每个优惠券的计数,使用:
_.countBy(result, "couponid")
其中result为数组
谁能告诉我,现在我怎样才能为每个唯一的优惠券 ID 获得多少个唯一的位置 ID(连同位置 ID)?即在上面的 couponid 500 将计数 2,而 couponid 600 将计数 1.
如果我理解正确的话,我想这会做你想做的事:
var result = _.chain(data)
.groupBy('couponid')
.mapObject( group => _.countBy(group, 'locationid'))
.value()
首先我们按 couponid
分组,然后映射该对象以计算该组中的每个 locationid
。
这将生成如下所示的对象:
{
500: {
10: 2,
20: 1
},
600: {
15: 1
}
}