【发布时间】:2021-12-27 11:31:37
【问题描述】:
我正在努力学习Array.reduce。我被赋予了以下任务:
输入数据:
const report = [
{
dateOfReport: "11-01-2021",
userId: "id1",
userMetric: { first_metric: 10, second_metric: 15 },
},
{
dateOfReport: "11-01-2021",
userId: "id2",
userMetric: { first_metric: 9, second_metric: 14 },
},
{
dateOfReport: "12-01-2021",
userId: "id1",
userMetric: { first_metric: 11, second_metric: 14 },
},
{
dateOfReport: "12-01-2021",
userId: "id2",
userMetric: { first_metric: 16, second_metric: 19 },
},
];
我需要在输出中获取这些数据
const output = [
{
dateOfReport: "11-01-2021",
id1: { first_metric: 10, second_metric: 15 },
id2: { first_metric: 9, second_metric: 14 },
},
{
dateOfReport: "12-01-2021",
id1: { first_metric: 11, second_metric: 14 },
id2: { first_metric: 16, second_metric: 19 },
},
];
我尝试编写一些代码,但我不知道如何正确执行。我该如何解决这个问题?
代码:
const result = report.reduce((acc, dataItem) => {
let outputArray = [];
if (dataItem) {
outputArray.push({ ...dataItem, date: dataItem.dateOfReport, [dataItem.userId]: dataItem.userMetric });
}
return outputArray;
});
return result;
【问题讨论】:
-
这能回答你的问题吗? How to group an array of objects by key
-
使用reduce函数,acc是累加器。基本上是一个对象,您可以给出一个初始值,并且在每次迭代中都在使用它。你不需要像 outputArray 这样的临时数组。
-
感谢您的信息
标签: javascript arrays reduce