Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a nested array from model in Ember?

So I have a model in Ember that is generating a hash with three objects. One of the objects is an array of objects with another array inside each object. I need to sort this innermost array, but I am having trouble doing so.

Here are my models.

App.Person = DS.Model.extend ({
    first_name: DS.attr('string'),
    last_name: DS.attr('string'),
    age: DS.attr('string'),
    gender: DS.attr('string'),
    innerMostArray: DS.hasMany('innerMostObject')
});

App.innerMostObject = DS.Model.extend ({
    person_id: DS.belongsTo('person'),
    attr1: DS.attr('string'),
    attr2: DS.attr('string')
});

Here is my Route

App.NestedArrayRoute = Ember.Route.extend({
    model: function(params) {
        return Ember.RSVP.hash({
            object1: this.store.find('object1', params.object1_id),
            people: this.store.all('person'),
            object3: this.store.all('object3')
        });
    },
    afterModel: function(model, transition) {
        model.people.forEach(function(item, index, enumerable){
            var innerMostArray = item.get('innerMostArray');
            var sortedArray = innerMostArray.sortBy('attr1', 'attr2');
        });
        model.people.update();
    } 
});

I know that I am nowhere near doing this right but I just don't know how to sort this nested array. I've seen examples of array controllers, but I don't know how to use one to sort this nested array. If anyone could give an example of how to do this it would be very helpful. Thank you.

like image 570
lfitzgibbons Avatar asked Feb 10 '23 18:02

lfitzgibbons


2 Answers

I agree with Kalmans answer, but I suggest you do this sorting with built-in methods to save you trouble:

App.Person = DS.Model.extend({
   name: DS.attr('string'),
   fruits: DS.hasMany('fruit', {async: true}),
   fruitSorting: ['title', 'color'],
   sortedFruits: Ember.computed.sort('fruits', 'fruitSorting')
});

I forked his example here: http://emberjs.jsbin.com/manutu/1/edit?html,js,output

like image 161
thriqon Avatar answered Feb 13 '23 07:02

thriqon


One way to do this is to create a computed property on the model as follows:

App.Person = DS.Model.extend({
  name: DS.attr('string'),
  fruits: DS.hasMany('fruit', { async: true }),
  sortedFruits: function(){
    var fruits = this.get('fruits');
    return fruits.sortBy('title', 'color');
  }.property('[email protected]', '[email protected]')
});

Working example here

like image 30
Kalman Avatar answered Feb 13 '23 07:02

Kalman