javascript - 对 JSON 数据中的分组数据进行格式化

标签 javascript jquery arrays json ecmascript-6

我正在尝试格式化从 JSON 获得的分组数据,但遇到困难。

这是我的对象数组:

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"
            }
          ]

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

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"}

有什么方法可以让我将数据格式化为如下所示:

{"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]}

如何将其格式化为如下所示?我的数据是动态的,因此我希望能够尽可能少地进行硬编码。

最佳答案

做类似的事情

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

关于javascript - 对 JSON 数据中的分组数据进行格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61603807/

相关文章:

javascript - 使用angularjs分页,所有页面显示相同的数据

javascript - 如何通过解析类信息用jQuery创建类

jquery - 使用 jQuery 从匹配特定格式的元素中删除所有类

javascript - 运行 Array 并添加/删除类

c - 在c中传递数组元素指针

javascript - 导出 Node.js 模块

javascript - Google Maps API,添加标记是否会影响使用限制?

javascript - Symfony2 收集字段,用于发送电子邮件的简单列表

javascript - Hammer JS 和历史

c - 为什么我会遇到段错误(多维数组 C)