【问题标题】:Transform an Array into an Object using .reduce()使用 .reduce() 将数组转换为对象
【发布时间】: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


【解决方案1】:

更正逻辑

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);

【讨论】:

    猜你喜欢
    • 2018-12-26
    • 2023-03-14
    • 2017-12-24
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    相关资源
    最近更新 更多