【问题标题】:Format nested dates without changing object structure在不更改对象结构的情况下格式化嵌套日期
【发布时间】:2021-12-10 04:50:30
【问题描述】:

我正在为此寻找一个好的清洁解决方案。我有一个可以输入 Date | 日期的对象空 |字符串:

someObject: {
    array: [
       {
          dateOne: '2021-10-21T22:00:00.000Z',
          dateTwo: '2021-10-21T22:00:00.000Z',
       }
    ];
 };

我正在寻找一个很好的解决方案,可以在不改变其结构的情况下将日期格式应用于上述内容。我知道下面的例子不起作用,它只是一个适用于对象中嵌套日期的例子,但可能是这些方面的东西。 示例如下:

someObject: Object.entries(values.someObject).reduce((acc, [a, b]) => {
                  if (b instanceof Date) {
                     return {
                        ...acc,
                        [a]: moment(b).format('YYYY-MM-DD'),
                     };
                  }
                  return acc;
               }, values.someObject),

预期输出:

    someObject: {
    array: [
       {
          dateOne: '2021-10-21',
          dateTwo: '2021-10-21',
       }
    ];
 };

TIA

【问题讨论】:

    标签: javascript arrays typescript object reduce


    【解决方案1】:

    您可以在此处使用splitmap

    const obj = {
      someObject: {
        array: [
          {
            dateOne: "2021-10-21T22:00:00.000Z",
            dateTwo: "2021-10-21T22:00:00.000Z",
          },
        ],
      },
    };
    
    function getFormattedDate(date) {
      return date.split("T")[0];
    }
    
    obj.someObject.array = obj.someObject.array.map(({ dateOne, dateTwo }) => ({
      dateOne: getFormattedDate(dateOne),
      dateTwo: getFormattedDate(dateTwo),
    }));
    
    console.log(obj);
    /* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
    
    .as-console-wrapper {
      max-height: 100% !important;
      top: 0;
    }
    /* Or in the context mentioned above */
    
    someObject: Object.entries(
                  values.someObject
               ).reduce((acc, [a, b]) => {
                  if (b[0].dateOne instanceof Date) {
                     return {
                        ...acc,
                        [b]: a.map(({ dateOne, dateTwo }) => ({
                           dateOne: moment(dateOne).format('YYYY-MM-DD'),
                           dateTwo: moment(dateTwo).format('YYYY-MM-DD'),
                        })),
                     };
                  }
                  return acc;
               }, values.someObject),
    

    【讨论】:

    • 非常感谢,我在上面的答案中添加了一个编辑,以便将您的逻辑添加到问题的上下文中。谢谢
    猜你喜欢
    • 2022-11-17
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-15
    相关资源
    最近更新 更多