【js】统计数组中某些项的个数
方法一:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript"> var arr = [ { group:"user", id:"2642ba0e_20da_fd20_7a99_97faebde4c57", title:"lisaWeb", tooltip:"", }, { group:"department", id:"2642ba0e_20da_fd20_7a99_97faebde4c57", title:"lisaWeb", tooltip:"", }, { group:"user", id:"2642ba0e_20da_fd20_7a99_97faebde4c57", title:"lisaWeb", tooltip:"", }, { group:"user", id:"2642ba0e_20da_fd20_7a99_97faebde4c57", title:"lisaWeb", tooltip:"", }, ]; var json = { 'user':0, 'department':0, 'label':0, 'post':0 } for(var i = 0 ; i < arr.length; i++){ for(key in json){ if(arr[i].group == key){ json[key]++ } } } console.log(json);//{user: 3, department: 1, label: 0, post: 0} </script> </head> <body> </body> </html>
方法二:利用reduce
var json = { 'user':0, 'department':0, 'label':0, 'post':0 } var temp = arr.reduce((pre,cur)=>{ if(cur.group in pre){ pre[cur.group] ++; } else { pre[cur.group] = 1; } return pre; },json) console.log(temp);
搜索
复制
作者:smile.轉角
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
欢迎关注我,一起进步!扫描下方二维码即可加我QQ
![](https://www.cnblogs.com/images/cnblogs_com/websmile/1492407/t_smile%E8%BD%AC%E8%A7%92.jpg)