Ramda:按嵌套对象分组

Ramda: group by nested object

我有这个数据:

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' } },
];

我需要将其作为输出:

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' }] },
];

我知道 ramda 中有 indexBy 但它不保留密钥以外的其他数据。我需要的是保留所有数据和 return 一个对象。

Ramda 的 groupBy 可以在这里帮助您:

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>     

因为需要从每个组中的第一个元素和整个组中提取部分,所以剩下的部分有点多,但总的来说,还不错: