0

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

1 Answer 1

1

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;
}

/* 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),
Sign up to request clarification or add additional context in comments.

1 Comment

Great thanks, I added an edit to your answer above to add your logic to the context of the question. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.