Sum of same object name in javascript

前端 未结 4 1458
[愿得一人]
[愿得一人] 2021-01-16 04:33

Hi friends I\'m beginner for javascript how i sum same n no\'s of object name corresponding value and push the result to new array.see this is sample object

va

相关标签:
4条回答
  • 2021-01-16 05:10

    Store these objects in an array, such as:

    var myObjects = [
        {'delivered':10,'due':11,'team_name':'UK'},
        {'delivered':10,'due':11,'team_name':'US'},
        {'delivered':10,'due':11,'team_name':'UK'}
    ];
    

    Create a new object in which you will store your results:

    var results = {};
    

    Then iterate through the array with a for loop (as it is generally faster) and add the other properties according to team_name:

    for (var i = 0; i <= myObjects.length; i++) {
        if (typeof results[myObjects[i].team_name] !== undefined) {
            results[myObjects[i]].delivered += myObjects[i].delivered;
            results[myObjects[i]].due += myObjects[i].due; 
        } else {
            // Set 0 to these properties if the entry didn't exist
            results[myObjects[i]].delivered = 0;
            results[myObjects[i]].due = 0;
        }
    }
    
    0 讨论(0)
  • 2021-01-16 05:12
    var obj_1 ={'delivered':10,'due':11,'team_name':'UK'};
    var obj_2 ={'delivered':10,'due':11,'team_name':'US'};
    var obj_nth ={'delivered':10,'due':11,'team_name':'UK'};
    
    function sum_all() { 
        var sum={}; 
        for(var i=0;i<arguments.length;i++) { 
            obj = arguments[i]; 
            if (!sum[obj.team_name]) { 
                sum[obj.team_name]={'delivered':0,'due':0}; 
            } 
            sum[obj.team_name].delivered += obj.delivered; 
            sum[obj.team_name].due += obj.due;    
        } 
        return sum; 
    }
    
    var sum = sum_all(obj_1,obj_2,obj_nth);
    
    console.log(sum);
    

    Your console output will be:

    sum
    Object
      UK: Object
          delivered: 20
          due: 22
    
      US: Object
          delivered: 10
          due: 11
    
    0 讨论(0)
  • 2021-01-16 05:27

    You can first create array of objects and then reduce() to return one object.

    var obj_1 ={'delivered':10,'due':11,'team_name':'UK'};
    var obj_2 ={'delivered':10,'due':11,'team_name':'US'};
    var obj_nth ={'delivered':10,'due':11,'team_name':'UK'};
    
    var result = [obj_1, obj_2, obj_nth].reduce(function(r, e) {
      if(!r[e.team_name]) {
        r[e.team_name] = {delivered:0,due:0}
      }
      r[e.team_name].delivered += e.delivered
      r[e.team_name].due += e.due
      return r
    }, {})
    
    console.log(result)

    0 讨论(0)
  • 2021-01-16 05:31
    const newArray = initialArray.map(({team_name, ...restProps}) => {
      return {
        [team_name]: {...restProps}
      };
    });
    

    See:

    • Arrow functions
    • Spread operator
    • Array.prototype.map
    • Computed property names
    0 讨论(0)
提交回复
热议问题