Sebastien D
Sebastien D

Reputation: 4482

Adding computed keys in a collection with lodash

Having the following example collection:

var data = [ 
  { 'fabrication_order' : 'A', 'start_date' : '2018-03-10 09:00:00', 'end_date' : '2018-04-12 10:30:00', 'product_family': 'car', 'price' : 70},
  { 'fabrication_order' : 'B', 'start_date' : '2018-03-14 12:00:00', 'end_date' : '2018-04-16 13:30:00', 'product_family': 'bike', 'price' : 20},
  { 'fabrication_order' : 'C', 'start_date' : '2018-03-14 13:00:00', 'end_date' : '2018-04-14 13:30:00', 'product_family': 'bike', 'price' : 20}
]

I can make stats using lodash :

stats = _(data)
   .groupBy('product_family')
   .map((objs, key) => ({
   'product_family' : key,
   'sum_price' : _.sumBy(objs, 'price')
   }))
   .value();

[ { "product_family": "car", "sum_price": 70 }, { "product_family": "bike", "sum_price": 40 } ]

Great. But what if I wanted to calculate the production duration. Is the only way is to transform my input data (before using lodash) by adding the custom fields :

data = data.forEach(function(element){
element['production_duration'] = moment(element.end_date).diff(moment(element.start_date), 'hours')
})

Or is there a more efficient way to achieve this?

Upvotes: 0

Views: 70

Answers (1)

C.Champagne
C.Champagne

Reputation: 5489

I'd rather use lodash for the whole thing.

You could have use the map method to add the duration property for each item as you almost did but the best is to use another sumBy in your last map call. What you maybe missed is that you can use a lambda with that function instead of the property name.

stats = _(data)
   .groupBy('product_family')
   .map((objs, key) => ({
   'product_family' : key,
   'sum_price' : _.sumBy(objs, 'price'),
   'sum_duration' : _.sumBy(objs, 
          (obj) => (moment(obj.end_date).diff(moment(obj.start_date), 'hours')))
   }))
   .value();

Upvotes: 1

Related Questions