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"
            }
        ]
    }
]

 

posted @ 2019-07-12 17:40  wjs0509  阅读(1028)  评论(0编辑  收藏  举报