从JSON数据格式化分组数据



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

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

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",
},
];
let result = arr.reduce((p, c) => {
let match = p.find(o => o.date_val === c.date);
if (match) {
match.metric_name.push(c.metric)
} else {
p.push({
date_val: c.date,
metric_name: [c.metric],
});
}
return p;
}, []);
console.log(result);

您可以使用array.reduce并根据指定字段动态评估结果键:

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

let group = (arr, val, name) => arr.reduce((acc, curr) => {
let valKey = val +"_val";
let nameKey = name + "_name";
let valValue = curr[val];
let nameValue = curr[name];

let existing = acc.find(x => x[valKey] === valValue);
if(existing){
existing[nameKey].push(nameValue);
} else {
acc.push({[valKey]: valValue, [nameKey]: [nameValue]})
}
return acc;
}, []);

console.log(group(arr, 'date', 'metric'))

最新更新