javascript 对后台返回的数据进行分类

模拟后台返回的数据为:

var arr = [
    {personName:"张三",id:1,age:12,gender:"male"},
    {personName:"张三",id:1,age:12,gender:"male"},
    {personName:"张三",id:1,age:12,gender:"male"},
    {personName:"李四",id:1,age:12,gender:"male"},
    {personName:"李四",id:1,age:12,gender:"male"},
    {personName:"李四",id:1,age:12,gender:"male"},
    {personName:"王五",id:1,age:12,gender:"male"},
    {personName:"王五",id:1,age:12,gender:"male"},
    {personName:"王五",id:1,age:12,gender:"male"}
]

对数据处理的方法为:(对personName来进行分类)

var nList = [];
for (var i = 0; i < arr.length; i++) {
    if (nList.length == 0) {
        nList.push({
            personName: arr[i].personName,
            data: [arr[i]]
        })
    } else {
        var index = nList.findIndex(item => item.personName == arr[i].personName);
        if (index >= 0) {
            nList[index].data.push(arr[i])
        } else {
            nList.push({
                personName: arr[i].personName,
                data: [arr[i]]
            })
        }
    }
}

对数据处理后的结构为:

[
    {
        "personName":"张三",
        "data":[
            {
                "personName":"张三",
                "id":1,
                "age":12,
                "gender":"male"
            },
            {
                "personName":"张三",
                "id":1,
                "age":12,
                "gender":"male"
            },
            {
                "personName":"张三",
                "id":1,
                "age":12,
                "gender":"male"
            }
        ]
    },
    {
        "personName":"李四",
        "data":[
            {
                "personName":"李四",
                "id":1,
                "age":12,
                "gender":"male"
            },
            {
                "personName":"李四",
                "id":1,
                "age":12,
                "gender":"male"
            },
            {
                "personName":"李四",
                "id":1,
                "age":12,
                "gender":"male"
            }
        ]
    },
    {
        "personName":"王五",
        "data":[
            {
                "personName":"王五",
                "id":1,
                "age":12,
                "gender":"male"
            },
            {
                "personName":"王五",
                "id":1,
                "age":12,
                "gender":"male"
            },
            {
                "personName":"王五",
                "id":1,
                "age":12,
                "gender":"male"
            }
        ]
    }
]

 

上一篇:MySQL外键及修改表和复制表


下一篇:python基础(第三章)布尔表达式+条件判断(下)