从JSON数据格式化分组数据 [英] Format grouped data from JSON data

查看:265
本文介绍了从JSON数据格式化分组数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试格式化从JSON获得的分组数据,但是这样做很麻烦。

I am trying to format the grouped data that I got from JSON but having trouble doing that.

这是我的对象数组:

arr = [
            {
                "date": "2020-01-01",
                "metric": 32,
                "type": "Google"
            },
            {
                "date": "2020-01-01",
                "metric": 24,
                "type": "Bing"
            },
            {
                "date": "2020-01-02",
                "metric": 1,
                "type": "Google"
            },
            {
                "date": "2020-01-02",
                "metric": 32,
                "type": "Jeeves"
            },
            {
                "date": "2020-01-03",
                "metric": 24,
                "type": "Bing"
            },
            {
                "date": "2020-01-03",
                "metric": 30,
                "type": "Google"
            }
          ]

我想按日期对所有指标进行分组。所以我做到了:

I want to group all the metrics by date. So I did this:

const groupBy = (array, key) => {
    return array.reduce((result, currentValue) => {
      (result[currentValue[key]] = result[currentValue[key]] || []).push(currentValue);
      return result;
    }, {});
};

const personGroupedByColor = groupBy(arr, 'date');

当我这样做时:

2020-01-01: 
0: {date: "2020-01-01", metric: 32, type: "Google"}
1: {date: "2020-01-01", metric: 24, type: "Bing"}
2020-01-02: 
0: {date: "2020-01-02", metric: 1, type: "Google"}
1: {date: "2020-01-02", metric: 32, type: "Jeeves"}
2020-01-03: 
0: {date: "2020-01-03", metric: 24, type: "Bing"}
1: {date: "2020-01-03", metric: 30, type: "Google"}

有什么办法让我格式化数据,使其看起来像这样:

Is there any way for me to format the data to look like so:

{"date_val": "2020-01-01", "metric_name": [32, 24]}
{"date_val": "2020-01-02", "metric_name": [1, 32]}
{"date_val": "2020-01-03", "metric_name": [24, 30]}

如何格式化它看起来像这样?我的数据是动态的,因此我希望能够尽可能减少硬编码。

How can I format it to look like this? My data is dynamic so I want to be able to hardcode as less as possible.

推荐答案

执行类似的操作

  Object.entries(personGroupedByColor).map(([key, group]) => ({
    ['date_val']: key,
    ['metric_name']: group.map(entry => entry.metric),
  }))

这篇关于从JSON数据格式化分组数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆