Skip to content

How do I transform the results of a Lodash groupBy in a _.chain

I have the following array:

[
  { user: 5fde62aa0cec1598fda103ac, feeling: 'positive' },
  { user: 5fde62a10cec1598fd9f9222, feeling: 'indifferent' },
  { user: 5fde62aa0cec1598fda103ac, feeling: 'positive' },
  { user: 5fde62a10cec1598fd9f9222, feeling: 'negative' },
  { user: 5fde62930cec1598fd9d426c, feeling: 'positive' }
]

After running it through .groupBy in a _.chain, I get the following:

 {
   '5fde62aa0cec1598fda103ac': { positive: 2 },
   '5fde62a10cec1598fd9f9222': { negative: 1, indifferent: 1 },
   '5fde62930cec1598fd9d426c': { positive: 1 }
 }

How can I then transform it to the following?

 [
   {id:'5fde62aa0cec1598fda103ac', positive: 2, negative: 0, indifferent: 0 }
   {id:'5fde62a10cec1598fd9f9222', positive: 0, negative: 1, indifferent: 1 }
   {id:'5fde62930cec1598fd9d426c', positive: 1, negative: 0, indifferent: 0}
 ]

I suspect that .transform is correct, just can’t figure out how to make it work.

Answer

_.transform(theData, function(result, value, key) {
  result.push({
    id : key, 
    positive: value.positive || 0, 
    negative: value.negative || 0, 
    indifferent: value.indifferent || 0 
  })
}, []);