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

后端 未结 14 893
借酒劲吻你
借酒劲吻你 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})
    
    0 讨论(0)
  • 2020-12-29 04:19

    This is the easiest approach I could think off

    var data = [{costOfAirtickets: 2500, costOfHotel: 1200},{costOfAirtickets: 1500, costOfHotel: 1000}];
    var sum ={};
    for(var obj in data){
      for(var ele in data[obj]){
        if(!data[obj].hasOwnProperty(ele)) continue;
          if(sum[ele] === undefined){
            sum[ele] = data[obj][ele];
          }else{
            sum[ele] = sum[ele] + data[obj][ele];
          }
      }
    
    }
    var arr = [sum];
    console.log(arr);
    
    0 讨论(0)
提交回复
热议问题