码迷,mamicode.com
首页 > Web开发 > 详细

js里JSON数据分组

时间:2020-10-22 23:07:35      阅读:36      评论:0      收藏:0      [点我收藏+]

标签:javascrip   var   key   return   class   分组   script   数据   new   

function GroupBy(arr,key) {
        var obj = {};
        for (let i = 0; i <arr.length; i++) {
            if (obj[arr[i][key]]) {
                obj[arr[i][key]].push(arr[i]);
            } else {
                obj[arr[i][key]] = new Array();
                obj[arr[i][key]].push(arr[i]);
            }
        }
        return obj;
    }

  

例如:

var data=[{
    "ID": "1",
    "Name": "张三",
    "Gender": "男",
    "Birthday": "2020-03-24 00:00:00"
}, {
    "ID": "2",
    "Name": "李四",
    "Gender": "男",
    "Birthday": "2020-03-23 00:00:00"
}, {
    "ID": "3",
    "Name": "王五",
    "Gender": "男",
    "Birthday": "2020-03-20 00:00:00"
}, {
    "ID": "4",
    "Name": "赵六",
    "Gender": "男",
    "Birthday": "2020-03-28 00:00:00"
}, {
    "ID": "5",
    "Name": "田七",
    "Gender": "女",
    "Birthday": "2020-03-25 00:00:00"
}];
console.log(GroupBy(data,"Gender"))
//输出{男: Array(4), 女: Array(1)}

  

js里JSON数据分组

标签:javascrip   var   key   return   class   分组   script   数据   new   

原文地址:https://www.cnblogs.com/kkvt/p/13860256.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!