Given an array of such objects:
var data = [ {key: 'a', val: '1'}, {key: 'a', val: '2'}, {key: 'b', val: '3'}, {key: 'c', val: '4'}, {key: 'c', val: '5'}, {key: 'c', val: '6'} ];
I would like to convert it to this:
var desiredResults = { 'a': [1, 2], 'b': [3], 'c': [4, 5, 6] };
I found two ways to achieve this so far with lodash-fp , but I'm still wondering if there is a better way.
The first method is somewhat procedural:
var out = _(data) .transform(function(out, item) { out[item.key] = out[item.key] || []; out[item.key].push(item.val); }, {});
The second way is the dot style that I was hoping to achieve:
var out = _(data) .groupBy(_.property('key')) .mapValues(_.map(_.property('val'))) .value();
However, this is more clutter than I would like: I need to iterate over the intermediate results in order to convert the grouped values, and I think it obscures what the code is trying to execute. I can’t convert first, though, since the conversion I want removes the keys!
Is there something like groupByTransforming(groupIteratee, transformIteratee) method?