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

Posted wjs0509

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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"
            
        ]
    
]

 

以上是关于javascript 对后台返回的数据进行分类的主要内容,如果未能解决你的问题,请参考以下文章

对后台返回的数据进行评分排序时间排序!

2后台分类页-多级分类列表

垃圾分类,javascript和python

电商后台管理项目d02

对返回的数据进行归类处理

使用两个 SQL 表为 Javascript 获取 JSON 数据