js根据某个字段进行分组
分组前数据:
[
{"f1":"q","f2":"w","f3":"e","f4":"r"},
{"f1":"q","f2":"w","f3":"e","f4":"r"},
{"f1":"w","f2":"w","f3":"e","f4":"r"},
{"f1":"w","f2":"w","f3":"e","f4":"r"},
]
分组后数据:
[
{"id":"q","data":"[{"f1":"q","f2":"w","f3":"e","f4":"r"},{"f1":"q","f2":"w","f3":"e","f4":"r"},]"},
{"id":"w","data":"[{"f1":"w","f2":"w","f3":"e","f4":"r"},{"f1":"w","f2":"w","f3":"e","f4":"r"},]"},
]
//根据字段分组
function getGroup(arr) {
var map = {},
dest = []; //处理后的数据
for (var i = 0; i < arr.length; i++) {
var ai = arr[i];
if (!map[ai.WSD_YEAR_MONTH]) {
dest.push({
id: ai.WSD_YEAR_MONTH,
data: [ai]
});
map[ai.WSD_YEAR_MONTH] = ai;
} else {
for (var j = 0; j < dest.length; j++) {
var dj = dest[j];
if (dj.id == ai.WSD_YEAR_MONTH) {
dj.data.push(ai);
break;
}
}
}
}
return dest;
}
本文来自博客园,作者:WantRemake,转载请注明原文链接:https://www.cnblogs.com/SmallChen/p/15633752.html