【问题标题】:Format array of data to object将数据数组格式化为对象
【发布时间】:2021-01-22 05:06:03
【问题描述】:

我有一组看起来像这样的数据

[
  {
    "title": "Appintment one",
    "allDay": false,
    "operators": [
      "600510d6d0ee8475bcb6de34"
    ],
    "start": "2021-01-25T14:48:00.000Z",
    "end": "2021-01-28T14:48:00.000Z",
  },
  {
    "title": "Appintment two",
    "allDay": false,
    "operators": [
      "600510d6d0ee8475bcb6de34"
    ],
    "start": "2021-01-26T14:48:00.000Z",
    "end": "2021-01-28T14:48:00.000Z",
  },
  {
    "title": "Appintment four",
    "allDay": false,
    "operators": [
      "600510d6d0ee8475bcb6de34"
    ],
    "start": "2021-01-26T14:48:00.000Z",
    "end": "2021-01-26T14:48:00.000Z",
  }
]

此数据是动态的,因此我可以进行 1 或 100 多个约会。我想要实现的是创建一个对象,其中键是格式化的start,值是包含当天约会的数组。

所以对于上述情况,

    {
25-01-2021: [
{
    "title": "Appintment one",
    "allDay": false,
    "operators": [
      "600510d6d0ee8475bcb6de34"
    ],
    "start": "2021-01-25T14:48:00.000Z",
    "end": "2021-01-28T14:48:00.000Z",
  }],
26-01-2021: [
{
    "title": "Appintment two",
    "allDay": false,
    "operators": [
      "600510d6d0ee8475bcb6de34"
    ],
    "start": "2021-01-26T14:48:00.000Z",
    "end": "2021-01-28T14:48:00.000Z",
  },
  {
    "title": "Appintment four",
    "allDay": false,
    "operators": [
      "600510d6d0ee8475bcb6de34"
    ],
    "start": "2021-01-26T14:48:00.000Z",
    "end": "2021-01-26T14:48:00.000Z",
  }
]

}

到目前为止,我只设法将格式化日期作为键,但值是一个对象,因此每个键只包含一个约会...

我的代码(使用时刻):

data.reduce((acc,curr)=> 
                (acc[moment(curr.start).format('DD-MM-YYYY')]=curr,acc),{});

【问题讨论】:

    标签: javascript arrays momentjs


    【解决方案1】:

    您可以使用array#reduce 根据日期对数据进行分组。

    const data = [ { "title": "Appintment one", "allDay": false, "operators": [ "600510d6d0ee8475bcb6de34" ], "start": "2021-01-25T14:48:00.000Z", "end": "2021-01-28T14:48:00.000Z", }, { "title": "Appintment two", "allDay": false, "operators": [ "600510d6d0ee8475bcb6de34"], "start": "2021-01-26T14:48:00.000Z", "end": "2021-01-28T14:48:00.000Z", }, { "title": "Appintment four", "allDay": false, "operators": [ "600510d6d0ee8475bcb6de34" ], "start": "2021-01-26T14:48:00.000Z", "end": "2021-01-26T14:48:00.000Z", } ],
          groupedByDate = data.reduce((r, o) => {
            const key = moment(o.start).format('DD-MM-YYYY')
            r[key] = r[key] || [];
            r[key].push(o);
            return r;
          },{});
    console.log(groupedByDate);
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous"></script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-10
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多