Sum all data in array of objects into new array of objects

后端 未结 14 954
借酒劲吻你
借酒劲吻你 2020-12-29 03:32

I have an array of objects that looks like this:

var data = [{costOfAirtickets: 2500, costOfHotel: 1200},{costOfAirtickets: 1500, costOfHotel: 1000}]
         


        
14条回答
  •  旧巷少年郎
    2020-12-29 04:11

    map the object and calculate the sum and store it in another.

    var data = [{costOfAirtickets: 2500, costOfHotel: 1200},{costOfAirtickets: 1500, costOfHotel: 1000}];
    var result = [];
    var sum = 0;
    var costsum = 0;
    data.map(function(item, key){
      var cost = item;
      //nsole.log(cost);
      sum = sum + cost.costOfAirtickets;
      costsum = costsum + cost.costOfHotel;
    
    });
    
    result = [{costOfAirtickets:sum, costOfHotel:costsum}];
    
    console.log(result);

提交回复
热议问题