如果我有一个像这样的对象数组:
{
"workPeriods": [
{
"user_id": "9345bf",
"startDate": "2018-02-05T05:00:00.000Z",
"endDate": "2018-02-09T05:00:00.000Z"
},
{
"user_id": "80c3a9",
"startDate": "2018-02-12T05:00:00.000Z",
"endDate": "2018-02-16T05:00:00.000Z"
},
{
"user_id": "35jh87",
"startDate": "2018-02-19T05:00:00.000Z",
"endDate": "2018-02-23T05:00:00.000Z"
}
]
}
打印每个对象日期范围内包含的所有日期的最佳方式是什么?
这需要使用 Moment jS 来完成
结果应该是这样的:
'Work days: 02/05, 02/06, 02/07, 02/08, 02/09, 02/12, 02/13, 02/14, 02/15, 02/16, 02/19, 02/20, 02/21, 02/22, 02/23'
有什么建议吗? 谢谢!
最佳答案
我不确定解决问题的“最佳”方法到底是什么意思,因为您没有指定评估解决方案的标准。看到functional-programming其他标签让我编写一些我认为相关的代码。
在下面的代码中(您可以test out here):
- 首先
map()
将每个工作周期转换为该周期中的一组天数。这将产生“数组的数组”。 reduce()
将数组扁平化为单个数组。- 然后,
map()
将每个 moment.jsMoment
对象格式化为其字符串表示形式。 - 最后,
join(' ')
将其转换为单个字符串,其中所有日期均以空格分隔。
如果您使用 ES6 或 TypeScript 编写:
const sourceObject = {
"workPeriods": [
{"user_id":"9345bf", "startDate":"2018-02-05T05:00:00.000Z", "endDate":"2018-02-09T05:00:00.000Z"},
{"user_id":"80c3a9", "startDate":"2018-02-12T05:00:00.000Z", "endDate":"2018-02-16T05:00:00.000Z"},
{"user_id":"35jh87", "startDate":"2018-02-19T05:00:00.000Z", "endDate":"2018-02-23T05:00:00.000Z"}
]
};
const userFriendlyWorkPeriodsDayList = sourceObject
.workPeriods
.map(workPeriod => {
const allDaysInRange = [];
const currentDate = moment(workPeriod.startDate);
const endDate = moment(workPeriod.endDate);
while (currentDate.isBefore(endDate)) {
allDaysInRange.push(currentDate.clone());
currentDate.add(1, 'days');
}
return allDaysInRange;
})
.reduce((accumulator, current) => (accumulator.push(...current), accumulator), [])
.map(date => date.format('MM/DD'))
.join(' ');
const result = `Work days: ${userFriendlyWorkPeriodsDayList}`;
<小时/>
在旧版本的 JavaScript 中重写的相同代码需要使用 function
关键字而不是 =>
。它们还可能缺乏扩展运算符支持 (.push(...arrayOfValuesBeingPushed)
)。
const sourceObject = {
"workPeriods": [
{"user_id":"9345bf", "startDate":"2018-02-05T05:00:00.000Z", "endDate":"2018-02-09T05:00:00.000Z"},
{"user_id":"80c3a9", "startDate":"2018-02-12T05:00:00.000Z", "endDate":"2018-02-16T05:00:00.000Z"},
{"user_id":"35jh87", "startDate":"2018-02-19T05:00:00.000Z", "endDate":"2018-02-23T05:00:00.000Z"}
]
};
const userFriendlyWorkPeriodsDayList = sourceObject
.workPeriods
.map(function (workPeriod) {
const allDaysInRange = [];
const currentDate = moment(workPeriod.startDate);
const endDate = moment(workPeriod.endDate);
while (currentDate.isBefore(endDate)) {
allDaysInRange.push(currentDate.clone());
currentDate.add(1, 'days');
}
return allDaysInRange;
})
.reduce(function (accumulator, current) { accumulator.push(...current); return accumulator; }, [])
.map(function (date) { return date.format('MM/DD'); })
.join(' ');
const result = `Work days: ${userFriendlyWorkPeriodsDayList}`;
console.log(result)
<小时/>
关于javascript - 打印数组内某些对象日期范围内包含的所有日期的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47984401/