网上找不到js分组的原生态方法,今天有空自己写了个方法,感觉还可以,拿出来分享,望各位读者多多指教。
1 $scope.groupBy = function (itemlist, gby) { 2 3 var setGroupObj = function (noteObj,rule, gby, gIndex, maxIndex) 4 { 5 var gname = rule[gby[gIndex]]; 6 if (gIndex == maxIndex) { 7 if (noteObj[gname] == undefined) 8 noteObj[gname] = []; 9 if (noteObj[gname].indexOf(rule) < 0) { 10 noteObj[gname].push(rule); 11 } 12 } 13 else { 14 if (noteObj[gname] == undefined) { 15 noteObj[gname] = {}; 16 } 17 setGroupObj(noteObj[gname], rule, gby, gIndex + 1, maxIndex); 18 } 19 } 20 21 var noteObj = {}; 22 for (var i = 0; i < itemlist.length; i++) { 23 setGroupObj(noteObj, itemlist[i], gby, 0, gby.length - 1); 24 } 25 26 27 var getSubInfo = function (note, p, gIndex, maxIndex) { 28 var newobj = {} 29 newobj.key = p; 30 newobj.value = []; 31 if (gIndex == maxIndex) { 32 for (var k in note) { 33 newobj.value.push(note[k]); 34 } 35 } 36 else { 37 for (var k in note[p]) { 38 newobj.value.push(getSubInfo(note[p][k], k, gIndex + 1, maxIndex)); 39 } 40 } 41 return newobj; 42 } 43 var myobj = []; 44 for (var p in noteObj) { 45 myobj.push(getSubInfo(noteObj, p, 0, gby.length - 1)); 46 } 47 return myobj; 48 } 49 $scope.groupRules = $scope.groupBy(allrules, [‘groupbycolumn1‘, ‘groupbycolumn2‘]);
其中allrules是要分组的数组,groupbycolumn1,groupbycolumn2是要进行分组的字段名,可以支持多个。
返回的结果是一个分组的对象:
var result={key:‘‘,value:[
{key:‘‘,value:[]},{key:‘‘,value:[]}
]}
时间: 2024-10-10 06:46:56