Combine an array of objects and their properties. Remove object after combining

后端 未结 4 1731
梦如初夏
梦如初夏 2021-01-29 08:18

I need to merge the objects together. The resource property is what determines if the objects can be merged. To determine where the hours property valu

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-29 08:32

    The problem is you're relying on the adjacent record of each record. Instead, you could keep a tally of each member by their resource. Since resource is unique, you can use it as a property of an object that keeps the tally -- think of it like a key. Then you can add the number of hours in each record to the appropriate object.

    Here's my attempt: http://codepen.io/anon/pen/bBYyPa

    var members = [
    {billable: true, hours: 15, name: "Joe Smith", resource: "00530000003mgYGAAY", totalBillableHours: 0, totalHours: 0, totalNonBillableHours: 0},
    {billable: true, hours: 5, name: "Joe Smith", resource: "00530000003mgYGAAY", totalBillableHours: 0, totalHours: 0, totalNonBillableHours: 0},
    {billable: false, hours: 5, name: "Joe Smith", resource: "00530000003mgYGAAY", totalBillableHours: 0, totalHours: 0, totalNonBillableHours: 0},
    {billable: false, hours: 5, name: "Jan Smith", resource: "00530000003mgYTAAY", totalBillableHours: 0, totalHours: 0, totalNonBillableHours: 0},
    {billable: true, hours: 12, name: "Jan Smith", resource: "00530000003mgYTAAY", totalBillableHours: 0, totalHours: 0, totalNonBillableHours: 0},
    {billable: true, hours: 2, name: "Jam Smith", resource: "00530000003mgYTAAY", totalBillableHours: 0, totalHours: 0, totalNonBillableHours: 0}  
    ];
    
    var membersObj = {};
    
    for (i = 0; i < members.length; i++) {
    
      var member = members[i];
      if (!membersObj[member.resource]){
        membersObj[member.resource] = members[i];
      }
    
      if(member.billable){
        membersObj[member.resource].totalBillableHours += member.hours;
      } else {
        membersObj[member.resource].totalNonBillableHours += member.hours;
      }
    
      membersObj[member.resource].totalHours += member.hours;
    
    }
    console.log(membersObj);
    

    Of course, this gives you back an object instead of an array, but that can be converted if necessary.

    Here is the output:

    { 
    '00530000003mgYGAAY': 
       { billable: true,
         hours: 15,
         name: 'Joe Smith',
         resource: '00530000003mgYGAAY',
         totalBillableHours: 20,
         totalHours: 25,
         totalNonBillableHours: 5 },
    '00530000003mgYTAAY': 
       { billable: false,
         hours: 5,
         name: 'Jan Smith',
         resource: '00530000003mgYTAAY',
         totalBillableHours: 14,
         totalHours: 19,
         totalNonBillableHours: 5 } 
    }
    

提交回复
热议问题