繁体   English   中英

使用moment js计算数组中所有对象的所有持续时间的总和

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM