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

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

    Here is a lodash approach

    _(data).flatMap(_.entries).groupBy(0).mapValues(v=>_.sumBy(v, 1)).value()
    

    It will sum by all the unique keys.

    var data = [{costOfAirtickets: 2500, costOfHotel: 1200},{costOfAirtickets: 1500, costOfHotel: 1000}];
    
    var res = _(data).flatMap(_.entries).groupBy(0).mapValues(v=>_.sumBy(v, 0)).value();
    
    console.log(res);

    Wrap your result to a [...] or use a .castArray() at the end before unwrapping using .value() in case you want a array as result.

提交回复
热议问题