1

我目前有一个日期数组,如下所示:

[
"2021-05-01",
"2021-05-02",
"2021-05-03",
]

在一个单独的条目数组中,我有包含与特定日期相关的日期的条目:

[
   {
      id: 5e24d1fa-aa66-4122-b1eb-97792f0893b0,
      name: "Rodriquez Family",
      selectedDates: ["2021-05-01"],
      status: "submitted"
    },
    {
      id: 269a0381-63c7-4ab6-92d8-7f7b836aee6f,
      name: "Test Family",
      selectedDates: ["2021-05-03"],
      status: "submitted"
    }
]

我正在尝试将两个数组配对以获得如下所示的结果:

 [
    {
      date: "2021-05-01",
      event: {
        id: 5e24d1fa-aa66-4122-b1eb-97792f0893b0,
        name: "Rodriquez Family",
        selectedDates: ["2021-05-01"],
        status: "submitted"
      }
    },
    {
      date: "2021-05-02",
      event: null
    },
    {
      date: "2021-05-03",
      event: {
        id: 269a0381-63c7-4ab6-92d8-7f7b836aee6f,
        name: "Test Family",
        selectedDates: ["2021-05-03"],
        status: "submitted"
      }
  ]

我遇到的问题是,当我遍历事件数组并检查事件是否具有属于日期数组中日期的选定日期时。它复制了许多事件的日期。我的函数如下所示:

const getDates = async () => {
      const addEvents = dateArr.map((date) => {
        return events.map((event) => {
          if (event.selectedDates.includes(date)) {
            return { date, event };
          }
          return { date, event: null, checked: false };
        });
      });
     console.log(addEvents.flat());
    };

我已经包含了一个使用 react 进行调试的 condesandbox!https://codesandbox.io/s/dawn-snow-03r59?file=/src/App.js代码沙箱将显示日期是如何被复制的。

4

1 回答 1

1

对于每个dateArr元素,您都在迭代events并返回具有两个指定选项的对象列表。相反,您可以使用Array#find它来检查它是否存在:

const 
  dateArr = ["2021-05-01", "2021-05-02", "2021-05-03"],
  events = [
    { id: "5e24d1fa-aa66-4122-b1eb-97792f0893b0", name: "Rodriquez Family", selectedDates: ["2021-05-01"], status: "submitted" },
    { id: "269a0381-63c7-4ab6-92d8-7f7b836aee6f", name: "Test Family", selectedDates: ["2021-05-03"], status: "submitted" }
  ];

const list = dateArr.map(date => {
  const event = events.find(({ selectedDates = [] }) => selectedDates.includes(date));
  return event ? { date, event } : { date, event: null, checked: false };
});

console.log(list);

于 2021-05-20T20:53:24.027 回答