我正在為此尋找一個很好的清潔解決方案。我有一個日期型別為 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
uj5u.com熱心網友回復:
您可以在此處使用split和map
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),
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/334916.html
標籤:javascript 数组 打字稿 目的 降低
上一篇:從陣列串列物件中洗掉值的類函式
下一篇:從陣列到物件并創建子類
