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

后端 未结 14 999
借酒劲吻你
借酒劲吻你 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 03:59

    Use Lodash to simplify your life.

    const _ = require('lodash')
    let keys = ['costOfAirtickets', 'costOfHotel']; 
    let results = _.zipObject(keys, keys.map(key => _.sum( _.map(data, key))))
    ...
    { costOfAirtickets: 4000, costOfHotel: 2200 }
    

    Explanation:

    • _.sum(_.map(data, key)): generates sum of each array
    • _.zipObject: zips the results with the array sum
    • using keys.map() for sum of each key as _.map does not guarantee order.

    Documentation:

    • sum: https://lodash.com/docs/4.17.10#sum
    • zipObject: https://lodash.com/docs/4.17.10#zipObject
    • map: https://lodash.com/docs/4.17.10#map

提交回复
热议问题