不得不说很牛
前端处理后端的返回来的json, 对数据进行处理类似group by,看到大牛的写法,分享给大家自己也做一下记录。
list = [
{"name": "John", "Average": 15, "High": 10, "DtmStamp": 1358226000000},
{"name": "Jane", "Average": 16, "High": 92, "DtmStamp": 1358226000000},
{"name": "Jane", "Average": 17, "High": 45, "DtmStamp": 1358226000000},
{"name": "John", "Average": 18, "High": 87, "DtmStamp": 1358226000000},
{"name": "Jane", "Average": 15, "High": 10, "DtmStamp": 1358226060000},
{"name": "John", "Average": 16, "High": 87, "DtmStamp": 1358226060000},
{"name": "John", "Average": 17, "High": 45, "DtmStamp": 1358226060000},
{"name": "Jane", "Average": 18, "High": 92, "DtmStamp": 1358226060000}
];
ngOnInit() {
const sorted = this.groupBy(this.list, function (item) {
return [item.name];
});
console.log(sorted);
}
groupBy(array, f) {
debugger;
const groups = {};
array.forEach(function (o) {
const group = JSON.stringify(f(o));
groups[group] = groups[group] || [];
groups[group].push(o);
});
return Object.keys(groups).map(function (group) {
return groups[group];
});
}
处理结果如下:
[
[
{
"name": "John",
"Average": 15,
"High": 10,
"DtmStamp": 1358226000000
},
{
"name": "John",
"Average": 18,
"High": 87,
"DtmStamp": 1358226000000
},
{
"name": "John",
"Average": 16,
"High": 87,
"DtmStamp": 1358226060000
},
{
"name": "John",
"Average": 17,
"High": 45,
"DtmStamp": 1358226060000
}
],
[
{
"name": "Jane",
"Average": 16,
"High": 92,
"DtmStamp": 1358226000000
},
{
"name": "Jane",
"Average": 17,
"High": 45,
"DtmStamp": 1358226000000
},
{
"name": "Jane",
"Average": 15,
"High": 10,
"DtmStamp": 1358226060000
},
{
"name": "Jane",
"Average": 18,
"High": 92,
"DtmStamp": 1358226060000
}
]
]
具体实现思路:
- 函数groupBy有两个形参,一为对象数组,二为匿名函数(该函数功能:返回对象的某个指定属性的属性值并存放在数组中);
- groupBy函数内,先创建一个空对象;
- 然后forEach遍历对象数组,遍历时要执行的函数中只有一个形参o(数组中的每个元素);
- 由于下面函数调用是想用name来分组,因此let group = JSON.stringify( f(o) ),相当于先获取到对象数组list中的name属性对应的属性值并放入数组中:["John"],然后再将属性值转换为json字符串:'["John"]';
- groups[group] = groups[group] || [],在js中对象也是关联数组,因此这里相当于做了两件事,一是把group作为groups的key,二是将对应的value初始化,第一次执行为空数组,循环执行时找到相同的name时保持不变;
- groups[group].push( o ),这句相当于把list中每个对象压入数组中作为value;
- 最后,Object.keys(groups)是取出groups对象中的所有key,然后遍历一个个key组成的新数组,返回分好了组的二维数组