Estoy buscando una buena solución limpia para esto. Tengo un objeto con fechas que pueden ser del tipo Fecha | nulo | cuerda:
someObject: { array: [ { dateOne: '2021-10-21T22:00:00.000Z', dateTwo: '2021-10-21T22:00:00.000Z', } ]; };
Estoy buscando una buena solución para aplicar el formato de fecha a lo anterior sin cambiar su estructura. Soy consciente de que el siguiente ejemplo no funcionaría, es solo un ejemplo que funcionaría para fechas anidadas en un objeto, pero tal vez algo similar. Ejemplo a continuación:
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),
Rendimiento esperado:
someObject: { array: [ { dateOne: '2021-10-21', dateTwo: '2021-10-21', } ]; };
AIT
Puede usar dividir y mapear aquí
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),