dagda1
dagda1

Reputation: 28810

Ember.js how to load an array of simple ember objects

What is the best way of creating an array of ember objects from an array of json objects objects?

I can use SetProperties on each individual object like this:

var ret = Ember.A();

pojos.forEach(function(obj){
  var em = Ember.Object.create({});
  emCluster.setProperties(obj);
  ret.push(emCluster);
});

But is there a one line way of obtaining the same result?

Upvotes: 7

Views: 5706

Answers (4)

user2646531
user2646531

Reputation: 23

ret = (Em.Object.create pojo for pojo in pojos)

Upvotes: 0

xamenrax
xamenrax

Reputation: 1744

I use this in my training-app to get json from remote server and parse it to array of objects.

App.Model.reopenClass({
  allItems: [],
  find: function(){
    $.ajax({
      url: 'http://remote_address/models.json',
      dataType: 'json',
      context: this,
      success: function(data){
        data.forEach(function(model){
          this.allItems.addObject(App.Model.create(model)) <-------------------
        }, this)
      }
    })
    return this.allItems;
  },
});

Upvotes: 0

ebryn
ebryn

Reputation: 4407

I'd map instead of using forEach:

pojos.map(function(obj){
  return Ember.Object.create().setProperties(obj);
});

Upvotes: 7

Mike Aski
Mike Aski

Reputation: 9236

Yep:

var ret = pojos.map(function(data) { return Ember.Object.create(data); });

Upvotes: 1

Related Questions