valerii15298
valerii15298

Reputation: 870

Ramda: group by nested object

I have this data:

const entities = [
  { id: 'view_1', group: { id: 'g_1', name: 'Group 1' } },
  { id: 'view_2', group: { id: 'g_2', name: 'Group 2' } },
  { id: 'view_3', group: { id: 'g_2', name: 'Group 2' } },
];

And I need to get this as output:

const groupedEntities = [
  { id: 'g_1', name: 'Group 1', views: [{ id: 'view_1' }] },
  { id: 'g_2', name: 'Group 2', views: [{ id: 'view_3' }, { id: 'view_3' }] },
];

I know there is indexBy in ramda but it does not preserve other data than key. What I need is to preserve all data and return an object.

Upvotes: 0

Views: 554

Answers (1)

Scott Sauyet
Scott Sauyet

Reputation: 50797

Ramda's groupBy can help you here:

const transform = pipe (
  groupBy (path (['group', 'id'])),
  values,
  map (applySpec ({
    group: path ([0, 'group', 'id']),
    name: path ([0, 'group', 'name']),
    views: pluck ('id')
  }))
)

const entities = [{id: 'view_1', group: { id: 'g_1', name: 'Group 1'}}, {id: 'view_2', group: { id: 'g_2', name: 'Group 2'}}, {id: 'view_3', group: { id: 'g_2', name: 'Group 2'}}]

console .log (transform (entities))
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js"></script>
<script>const {pipe, groupBy, path, values, map, applySpec, pluck} = R</script>     

The rest of it is a bit more of a handful because of the need to pull parts from the first element in each group and parts from the whole group, but overall, it's not too bad:

Upvotes: 1

Related Questions