![](/img/trans.png)
[英]How to Handle Durations Without Using Moment.js Durations Feature?
[英]Calculate the sum of all durations of all objects in array using moment js
我得到對象數組,它們都有字段持續時間,即一個字符串; 對象示例:
{
id: 14070
project: {id: 87, name: "Test project for time tracking"}
issue: {id: 10940}
user: {id: 107, name: "Alexander Kirillov"}
activity: {id: 9, name: "Development"}
hours: 0.01
comments: "RARA"
spent_on: "2020-03-23"
created_on: "2020-03-23T14:58:18Z"
updated_on: "2020-03-23T14:58:26Z"
custom_fields: (2) [{…}, {…}]
start: "Mon, 23rd Mar"
duration: "00:01" // HH:mm
__proto__: Object
}
數組名稱是 timeEntries = [{},{},...]; 如何使用moment js計算timeEntries中所有對象的所有持續時間的總和? 先謝謝了!!!
你可以這樣實現:
const timeEntries = [{ duration: "00:01" }, { duration: "01:00" }, { duration: "12:30" } ]; const totalDurations = timeEntries.slice(1) .reduce((prev, cur) => { return prev.add(cur.duration); }, moment.duration(timeEntries[0].duration)); console.log(`Total duration is: ${moment.utc(totalDurations.asMilliseconds()).format("HH:mm")}`);
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
我找到了解決方案:
const totalDurations = durations.split(1).reduce(
(prev, cur) => moment.duration(cur).add(prev),
moment.duration(durations[0])
).format("HH:mm");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.