js对数据分组类似group by

不得不说很牛

前端处理后端的返回来的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
    }
  ]
]

具体实现思路:

  1. 函数groupBy有两个形参,一为对象数组,二为匿名函数(该函数功能:返回对象的某个指定属性的属性值并存放在数组中);
  2. groupBy函数内,先创建一个空对象;
  3. 然后forEach遍历对象数组,遍历时要执行的函数中只有一个形参o(数组中的每个元素);
  4. 由于下面函数调用是想用name来分组,因此let group = JSON.stringify( f(o) ),相当于先获取到对象数组list中的name属性对应的属性值并放入数组中:["John"],然后再将属性值转换为json字符串:'["John"]';
  5. groups[group] = groups[group] || [],在js中对象也是关联数组,因此这里相当于做了两件事,一是把group作为groups的key,二是将对应的value初始化,第一次执行为空数组,循环执行时找到相同的name时保持不变;
  6. groups[group].push( o ),这句相当于把list中每个对象压入数组中作为value;
  7. 最后,Object.keys(groups)是取出groups对象中的所有key,然后遍历一个个key组成的新数组,返回分好了组的二维数组
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值