使用.duce()将数组转换为对象
我正在努力学习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;
解决方案
更正逻辑
数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">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 result = report.reduce((acc, dataItem) => {
const node = acc.find(item => item.dateOfReport === dataItem.dateOfReport);
if (node) {
node[dataItem.userId] = dataItem.userMetric;
} else {
acc.push({ dateOfReport: dataItem.dateOfReport, [dataItem.userId]: dataItem.userMetric });
}
return acc;
}, []);
console.log(result);
相关文章