码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-07-12 18:59:21      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:push   script   java   lis   nbsp   处理   结构   find   end   

模拟后台返回的数据为:

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

 

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

标签:push   script   java   lis   nbsp   处理   结构   find   end   

原文地址:https://www.cnblogs.com/wjs0509/p/11177513.html

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