模拟后台返回的数据为:
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" } ] } ]
原文地址:https://www.cnblogs.com/wjs0509/p/11177513.html
时间: 2024-10-13 11:07:37