Home > Back-end >  Format nested dates without changing object structure
Format nested dates without changing object structure

Time:10-24

I am looking for a good clean solution for this. I have an object with dates that can be type Date | null | string:

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

I am looking for a good solution to apply date formatting to the above without changing its structure. I am aware that the below example would not work, its just an example that would work for nested Dates in an object, but maybe something along these lines. Example below:

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

Expected output:

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

TIA

CodePudding user response:

You can use split and map here

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;
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

/* 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),
  • Related