【Javascript】数组扩展方法:根据key重新分组
1 //数组扩展:根据key重新分组 2 //field:按什么字段分组 3 Array.prototype.GroupByKey = function ( field ) 4 { 5 var originalArr = this 6 let tempArr = [] 7 let resultData = [] 8 for ( let i = 0; i < originalArr.length; i++ ) 9 { 10 if ( tempArr.indexOf( originalArr[ i ][ field ] ) === -1 ) 11 { 12 resultData.push( { 13 [ field ]: originalArr[ i ][ field ], 14 data: [ originalArr[ i ] ] 15 } ) 16 tempArr.push( originalArr[ i ][ field ] ) 17 } else 18 { 19 for ( let j = 0; j < resultData.length; j++ ) 20 { 21 if ( resultData[ j ][ field ] == originalArr[ i ][ field ] ) 22 { 23 resultData[ j ].data.push( originalArr[ i ] ) 24 break 25 } 26 } 27 } 28 } 29 return resultData // 最终输出 30 }
使用例子:
var scoreArr = [ { name: "小明", subject: "语文", score: 88 }, { name: "小明", subject: "数学", score: 58 }, { name: "小红", subject: "数学", score: 85 }, { name: "小红", subject: "语文", score: 99 }, ] var resultArr = scoreArr.GroupByKey( "name" )
得到结果:
[ { name: "小明", data: [ { name: "小明", subject: "语文", score: 88 }, { name: "小明", subject: "数学", score: 58 } ] }, { name: "小红", data: [ { name: "小红", subject: "数学", score: 85 }, { name: "小红", subject: "语文", score: 99 } ] } ]