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

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

    var data = [{costOfAirtickets: 2500, costOfHotel: 1200},{costOfAirtickets: 1500, costOfHotel: 1000}];
    
    var result = [data.reduce((acc, n) => {
      for (var prop in n) {
        if (acc[prop]) acc[prop] += n[prop];
        else acc[prop] = n[prop];
      }
      return acc;
    }, {})]
    console.log(result)

提交回复
热议问题