简体   繁体   中英

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.

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM