【发布时间】:2020-08-19 13:30:24
【问题描述】:
我正在尝试格式化从 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