1

我正在开发一个日历应用程序,它有一个来自“react-native-calendars”的议程。要显示日期,它需要以下内容:

items={{'2012-05-22': [{name: 'item 1 - any js object'}], ...}}

在我的firebase后端中,我存储了约会的开始和结束日期以及一个数组,其中包括它的每一天(因此,如果约会从昨天开始到明天结束,则数组将昨天、今天和明天存储为日期。数组中的日期数量不同!)

api数据结构如下:

apiData = [
          {data: {allDays: ["2021-08-18", "2021-08-19", "2021-08-20"],
                  start: "2021-08-18",
                  end: "2021-08-20"
                  },
           id: "string"},
          {data: {allDays: ["2021-08-20", "2021-08-21", "2021-08-22", "2021-08-23"],
                  start: "2021-08-20",
                  end: "2021-08-23"
                  },
           id: "string"},
           //more Data
           ]

我得到以下代码来映射文档:

let markedDayAll = {};

{apiData.map(({data: {start, end, allDays}}) => (
    markedDayAll[alldays] = [{
      start: start,
      end: end
    }]
  ))};

它以正确的“项目”格式输出,但现在,显然,它显示如下:

items={{
   '2021-08-18, 2021-08-19, 2021-08-20': [{start: "2021-08-18, end: "2021-08-20}]
   }}

但我需要以下内容:

items={{
   '2021-08-18': [{start: "2021-08-18, end: "2021-08-20}],
   '2021-08-19': [{start: "2021-08-18, end: "2021-08-20}],
   '2021-08-20': [{start: "2021-08-18, end: "2021-08-20}]
   }}

如何正确映射数据,从而获得所需的结果?

4

1 回答 1

2

您可以使用array#reduce来遍历每个对象,然后遍历每个日期allDays并生成您的对象。

const apiData = [ {data: {allDays: ["2021-08-18", "2021-08-19", "2021-08-20"], start: "2021-08-18", end: "2021-08-20" }, id: "string"}, {data: {allDays: ["2021-08-20", "2021-08-21", "2021-08-22", "2021-08-23"], start: "2021-08-20", end: "2021-08-23" }, id:"string"} ],
      result = apiData.reduce((r, {data}) => {
        data.allDays.forEach(date => {
          r[date] ??= [];
          r[date].push({start: data.start, end: data.end});
        });
        return r;
      },{});
console.log(result);

于 2021-08-19T14:12:35.693 回答