簡體   English   中英

如何計算總時數?

[英]How to calculate total hours?

我正在嘗試根據“ employeeId”計算總時數。 我不知道如何為此編寫邏輯。 解決此問題的最佳方法是什么?

預期結果,

[
    {

        "employeeId": "105",
        "totalHours": "2:45"
    },
    {
        "employeeId": "777",
        "totalHours": "2:15"
    }
]

來自Ajax Call的回復

[
    {
        "employeeId": "105",
        "totalHours": "1:30"
    },
    {
        "employeeId": "777",
        "totalHours": "1:15"
    },
    {
        "employeeId": "105",
        "totalHours": "1:15"
    },
    {
        "employeeId": "777",
        "totalHours": "1:00"
    }
]

我的密碼

var jrr = new Array();
    Ext.Ajax.request({
      url: '/common/services/general/basicOperations/getDataByModelUsingGetMethod',
      method: 'GET',
      params : {
        actionId : 'payroll',
        dataJson : '{"aspectType":"Payroll Profile"}'
      },
      success: function(response){
        try{
          var response = response.responseText;
          var resObj = Ext.decode(response);
          for(var j = 0; j < resObj.data.length; j++)
              {
                 for(var k = 0; k < resObj.data[j].payrolltransactionDetail.length; k++) 
                 {
                    jrr.push(resObj.data[j].payrolltransactionDetail[k]);
                 }
              }
              console.log(JSON.stringify(jrr, null, 4));
        }
        catch(e){
          console.log(e);
        }
      },
      failure: function(response){
        deferred.reject("Error Fetching.");
      }
    });

這是使用js函數式編程的實現。 您可以僅使用reduce函數將數據轉換為所需的輸出。 如果您無法在服務器端使用某種聚合來更改查詢結果,則可以實施類似於以下內容的方法。

 var input = [ { "employeeId": "105", "totalHours": "1:46" }, { "employeeId": "777", "totalHours": "1:15" }, { "employeeId": "105", "totalHours": "1:15" }, { "employeeId": "777", "totalHours": "1:00" } ] var obj = input.reduce( function(init, e){ //if aggregating init object doesn't have the employee then add the employeeId (key) and time (value) if (init[e["employeeId"]] == undefined){ init[e["employeeId"]] = { hours: parseInt(e["totalHours"].split(":")[0]), minutes: parseInt(e["totalHours"].split(":")[1]) }; init[e["employeeId"]].timeString = e["totalHours"]; return init; //otherwise add to the existing employeeId the hour and minute values, while remembering to carry the extra hour if minutes exceed 59. }else{ init[e["employeeId"]].hours += (parseInt(e["totalHours"].split(":")[0]) + Math.floor((init[e["employeeId"]].minutes + parseInt(e["totalHours"].split(":")[1]))/60)); init[e["employeeId"]].minutes = (init[e["employeeId"]].minutes + parseInt(e["totalHours"].split(":")[1]))%60; init[e["employeeId"]].timeString = init[e["employeeId"]].minutes > 9 ? init[e["employeeId"]].hours + ":" + init[e["employeeId"]].minutes : init[e["employeeId"]].hours + ":0" + init[e["employeeId"]].minutes; return init; } }, {}); var arr = []; for (var prop in obj) arr.push({employeeId: prop, totalHours: obj[prop].timeString}); console.log(arr); 

這是一個實現。 我認為它比其他一些答案還干凈:

function calc(data) {
    const seen = {};
    const result = [];

    data.forEach(item => {
        const id = item.employeeId;
        if (!seen.hasOwnProperty(id)) {
            seen[id] = result.length;
            result.push({
                employeeId: id,
                minutes: 0
            });
        }
        const idx = seen[id];
        const parts = item.totalHours.split(':');
        result[idx].minutes += (parseInt(parts[0], 10) * 60) + parseInt(parts[1]);
    });

    result.forEach(item => {
        const minutes = item.minutes;
        delete item.minutes;
        item.totalHours = Ext.String.leftPad(Math.floor(minutes / 60), 2, '0') 
                            + ':' + Ext.String.leftPad(minutes % 60, 2, '0');
    });

    return result;
}

console.log(calc([{
    "employeeId": "105",
    "totalHours": "1:30"
}, {
    "employeeId": "777",
    "totalHours": "1:15"
}, {
    "employeeId": "105",
    "totalHours": "1:15"
}, {
    "employeeId": "777",
    "totalHours": "1:00"
}]));

在函數頂部添加:

var totalHours = 0;

然后內部循環是:

for(employee in resObj.data[j].payrolltransactionDetail) {
    totalHours += employee.totalHours;
}

然后您可以使用它,但是在外循環之后您認為合適。 如果要對每個transactionDetail求和,請確保在內循環之前將其重置為0,在內循環之后使用。

//  Expecting input to be your custom object
var output={};
for(i=0;i<input.length;i++){
el = input[i];
a=output[el.id];
a.employeId=el.employeId;
a.totalHours=a.totalHours||"0:0";
b=el.totalHours.split(":");
c=a.totalHours.split(":");
b[0]=+b[0]+c[0];
if(b[1]+c[1]>60){
b[0]++;
}
b[1]=(+b[1]+c[1])%60;
a.totalHours=b.join(":");
}

結果並不完全符合您的預期。 我不想每次在數組中搜索員工ID:

{
105:{
   employeid:105;
   totalHours:"15:20";
 }
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM