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

后端 未结 14 1000
借酒劲吻你
借酒劲吻你 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:15

    Try using reduce only as in the below snippet. Try avoiding multiple iterations. Hope the below snippet helps!

    var data = [{costOfAirtickets: 2500, costOfHotel: 1200},{costOfAirtickets: 1500, costOfHotel: 1000}]
    
    var total = data.reduce(function (result,value,key) {
    result['costOfAirtickets'] = result['costOfAirtickets']  + value['costOfAirtickets'];
    result['costOfHotel'] = result['costOfHotel']  + value['costOfHotel'];
    
    return result},{costOfAirtickets:0,costOfHotel:0});
    
    console.log(total)

提交回复
热议问题