Laura Silvani
Laura Silvani

Reputation: 757

Javascript - GroupBy key and how to model the resulting object

I have this array of items:

[
  {id: 1, label: 'test', parent: 'parent 1'},
  {id: 2, label: 'fool', parent: 'parent 1'},
  {id: 3, label: 'bla', parent: 'parent 2'},
  {id: 4, label: 'foo', parent: 'parent 2'}
]

and I am trying to get something like this out of it:

[
  {parent: 'parent 1', members: [{id: 1, label: 'test'}, {id: 2, label: 'fool']},
  {parent: 'parent 2', members: [{id: 3, label: 'bla'}, {id: 4, label: 'foo']}
]

Using underscore.js I am able to get to this point:

_.groupBy(myList,'parent')
=> 
{
  'parent 1': [{id: 1, label: 'test'}, {id: 2, label: 'fool'],
  'parent 2': [{id: 3, label: 'bla'}, {id: 4, label: 'foo'],
}

...which is not exactly what I want. I am pretty sure it is something stupid but getting kind of stucked :(

Upvotes: 4

Views: 225

Answers (1)

Laura Silvani
Laura Silvani

Reputation: 757

Ok, found the answer here Group objects by property in javascript

So the groupBy now is encapsulated in a chain and the result is passed to the _.map function:

.chain(myList)
      .groupBy('parent')
      .map(function(value, key) {
        return {
          parent: key,
          members: value
      }
    })
    .value()

Upvotes: 2

Related Questions