[格式化JSON数据中的分组数据

问题描述 投票:2回答:1

我正在尝试格式化从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]}

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

javascript jquery arrays json ecmascript-6
1个回答
0
投票

您可以reduce()数组并检查累加器中是否已存在给定日期,如果是,则将当前日期推入该日期,否则用数组中的该日期创建一个新对象:

reduce()
© www.soinside.com 2019 - 2024. All rights reserved.