How to make a filter group in Aurelia

I'm looking for a way to do something like

Js

$scope.players = [ {name: 'Gene', team: 'alpha'}, {name: 'George', team: 'beta'}, {name: 'Steve', team: 'gamma'}, {name: 'Paula', team: 'beta'}, {name: 'Scruath', team: 'gamma'} ]; 

HTML:

 <ul repeat.for="obj of players | groupBy: 'team'"> Group name: ${obj.group} <li repeat.for="player of obj.values"> player: ${player.name} </li> </ul> 

Can this be done? Or what is the best way to do this logic in Aurelia?

+6
source share
3 answers

You can do this using ValueConverter .

 export class GroupByValueConverter { toView(array, groupBy) { var groups = {}; array.forEach(function (o) { var group = o[groupBy]; groups[group] = groups[group] || []; groups[group].push(o); }); return Object.keys(groups).map(function (group) { return { group: group, values: groups[group] }; }) } } 
+4
source

Having received this answer, I did it a little differently. Instead of using an array of objects with the group and value keys, I used Map .

Updated view

 <ul repeat.for="[group, values] of players | groupBy:'team'"> Group name: ${group} <li repeat.for="player of values"> player: ${player.name} </li> </ul> 

For the value converter, I used this answer for inspiration on an effective way to execute a group by action.

Value converter

 export class GroupByValueConverter { toView(objects, key) { return objects.reduce( (rv, x) => rv.set(x[key], (rv.get(x[key]) || []).concat(x)), new Map() ); } } 
0
source

The ValueConverter extension above allows you to use a grouping filter with properties of nested objects (for example, groupBy: 'team.id')

 export class GroupByValueConverter { toView(array, groupBy) { var groups = {}; var props = groupBy.split("."); array.forEach(function (o) { var group = o; props.forEach(function (p) { group = group[p] }); groups[group] = groups[group] || []; groups[group].push(o); }); return Object.keys(groups).map(function (group) { return { group: group, values: groups[group], }; }) } } 

Another extension that allows you to specify as an object group. A second parameter is required to specify the key of the object to be used as the indexer.

eg. - | GroupBy: 'team': 'ID' - | group: 'projectMember.team': 'identifier'

 export class GroupByValueConverter { toView(array, groupBy, groupByKey) { var groups = {}; var groupMembers = {}; var props = groupBy.split("."); array.forEach(function (o) { var group = o; props.forEach(function (p) { group = group[p] }); var index = groupByKey && group ? group[groupByKey] : group; groups[index] = group; groupMembers[index] = groupMembers[index] || []; groupMembers[index].push(o); }); return Object.keys(groups).map(function (index) { return { group: groups[index], values: groupMembers[index], }; }) } } 
0
source

All Articles