HaoQi Li
HaoQi Li

Reputation: 12348

How to get an array containing the values of an attribute for an Ember model?

For example if I have a Person model with the "name" attribute, what can I call in Ember.js with Ember Data that returns an array of all the names in the Person model?

Upvotes: 1

Views: 1275

Answers (2)

Mike Grassotti
Mike Grassotti

Reputation: 19050

App.Person.find().then( function(data) {
  var namesArray = data.getEach('name');
});

UPDATE RE: COMMENT (what if i want to do this from setupController...)

setupController: function(controller, model) {
  App.Person.find().then( function(data) {
    controller.set('variablename', data.getEach('name') };
  });
}

Upvotes: 3

Panagiotis Panagi
Panagiotis Panagi

Reputation: 10087

App.PersonsRoute = Ember.Route.find({
  setupController: function() {
    // Get all persons
    this.controllerFor('persons').set('content', App.Person.find());
  } 
});


App.PersonsController = Ember.ArrayController.extend({
  allNames: function() {
    var persons = this.get('content') || [];
    return persons.getEach('name');
  }.property('content.[]')
});

In short, when you have a collection (an array of objects) and you want to build a new array of the values of a certain property, use getEach. getEach('foo') is an alias for mapProperty('foo').

Upvotes: 2

Related Questions