使用 lodash 或 underscorejs 查找字段的数组计数
Find array count of fields using lodash or underscorejs
我有一个要求,获取数组中每种帐户类型的计数。我已经尝试了循环数组的正常方法,并为每个数组增加一个计数器account_type。你能帮我在 lodash 或下划线 js 中做同样的事情吗?
非常感谢您的帮助。谢谢。
input_array = [
{
account_id: '4304bf0381140b8fcccbdddea3571a53facebook',
account_type: 'facebook'
},
{
account_id: '4304bf0381140b8fcccbdddea332434facebook',
account_type: 'facebook'
},
{
account_id: '5824fb40c4a97e21ef9715ea69c1cfb9twitter',
account_type: 'twitter'
},
{
account_id: '5824fb40c4a97e21ef9715ea432423twitter',
account_type: 'twitter'
},
{
account_id: '2c13790be20a06a35da629c71e548afexing',
account_type: 'xing'
},
{
account_id: 'd1376b07b144130c4f041e223dfb1197weibo',
account_type: 'weibo'
},
{
account_id: 'd1376b07b144130c4f041e223df4343weibo',
account_type: 'weibo'
}
]
output_array = [
{
type: "facebook",
count: 2
},
{
type: "twitter",
count: 2
},
{
type: "xing",
count: 1
},
{
type: "weibo",
count: 2
}
]
试
input_array.forEach(function(data){
if(data.account_type=='facebook'){
count++;//forfacebook
}
});
您可以使用
countBy
...
_.countBy(input_array, function(obj) {
return obj.account_type;
});
您可以使用
filter()
var arrLen = _.filter(input_array, function(obj){
console.log(obj)
return obj.account_type === "facebook"
}).length;
相关文章:
- 如何在 for 循环中访问 json 数组字段的名称
- 如何通过向用户推送模式引用来更新用户对象's数组字段
- 访问嵌套的 json 数组字段
- PHP 从“选择 - 数组”字段中填充文本框
- 在 Rally SDK 2 中,如何更新数组字段,例如在变更集的工件上
- 遍历 html 模板中的数组字段
- 如何通过按数组字段选择来检索MongoDB文档
- Jquery 添加未传递给 php 的输入数组字段
- 如何在JSON数组字段的基础上从主干集合中提取模型
- 引用到另一个类的数组字段数组字段没有't刷新
- PHP中的HTML数组字段解析
- mongoose.js:我如何从引用的子数组中删除一个属性,同时使用填充和使用其中一个子数组字段作为过滤器
- js serialize()可以处理数组字段名吗?
- 在数组字段上展平嵌套的对象数组
- 如何在mongodb的子文档模式结构中更新数组字段
- 数组字段的弹性搜索日期范围过滤器
- 当数组字段为空时,替换值不能正常工作
- 如何从dc.js / crossfilter / d3中的数组字段中选择元素,并将每个元素用作图表的单独数据点
- 当我从模型中的数组字段中添加或删除对象时,Ember不更新模板
- 从javascript中设置postgres数组字段为null