在不更改对象结构的情况下格式化嵌套日期
Format nested dates without changing object structure
我正在为此寻找一个好的清洁解决方案。我有一个对象,其日期类型可以是 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
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),
我正在为此寻找一个好的清洁解决方案。我有一个对象,其日期类型可以是 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
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),