Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show a simple group by header while you enumerate an array in handlebars with ember?

Tags:

ember.js

I have an array of ember objects that share a common attribute like "group"

var first = {name: 'first', group: 'A'}
var middle = {name: 'middle', group: 'B'}
var last = {name: 'last', group: 'A'}

{{#each person in controller}}
{{person.name}}
{{/each}}

How can I show the group name as a "header" only once for each group? I was doing something like the below (creating a custom "object" with a key for the group and a "custom array" for the value -but the problem is I can't have a nested computed property so this didn't seem ideal long term)

groupby: function(content) {
  var all = Ember.A([]);
  content.map(function(apt) {
    var employee = apt.get('employee').get('name');
    var match = all.filter(function(group) {
      if (group.name === employee) {
        return group;
      }
    });
    if (match.length > 0) {
      match[0].appointments.pushObject(apt);
    }else{
      var group = Ember.Object.create({'name': employee, appointments: [apt]});
      all.pushObject(group);
    }
  });
  return all;
}.property()
like image 289
Toran Billups Avatar asked Nov 01 '22 04:11

Toran Billups


1 Answers

I ended up with this solution

grouped_by: function() {
  var result = [];
  var content = this.get('content');
  content.forEach(function(item) {
    var name = item.get('group_name');
    var found = result.findBy('name', name);
    if(!found) {
      result.pushObject(Ember.Object.create({name: name, contents: []}));
    }
    result.findBy('name', name).get('contents').pushObject(item);
  });
  return result;
}.property('[email protected]_name')
like image 69
Toran Billups Avatar answered Jan 04 '23 15:01

Toran Billups