我正在努力學習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;
uj5u.com熱心網友回復:
更正了邏輯
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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/357455.html
標籤:javascript 数组 降低
上一篇:加載JSON檔案并列印特定部件
下一篇:無法分配給函式呼叫
