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

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

    You don't need to map the array, you're really just reducing things inside it.

    const totalCostOfAirTickets: data.reduce((prev, next) => prev + next.costOfAirTickets, 0)
    const totalCostOfHotel: data.reduce((prev, next) => prev + next.costOfHotel, 0)
    const totals = [{totalCostOfAirTickets, totalCostOfHotel}]
    

    In one go, you could do something like

    const totals = data.reduce((prev, next) => { 
        prev.costOfAirTickets += next.costOfAirTickets; 
        prev.costOfHotel += next.costOfHotel; 
    }, {costOfAirTickets: 0, costOfHotel: 0})
    

提交回复
热议问题