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

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

    To create a resultant / reduced value, you should use .reduce() method instead of .map():

    let data = [
      {costOfAirtickets: 2500, costOfHotel: 1200},
      {costOfAirtickets: 1500, costOfHotel: 1000}
    ];
    
    let result = data.reduce(
      (a, c) => (Object.keys(c).forEach(k => (a[k] = (a[k] || 0) + c[k])), a), {}
    );
    
    console.log(result);

提交回复
热议问题