Qrilka Qrilka - 6 days ago 4
Javascript Question

Is there any way to convert Ember Object into plain javascript object?

I could not find any way to accomplish the task of such conversion as I could not find any means of getting Ember.js properties for the object.

Ember.keys
returns only the properties I set in
create
or with
get
and the properties declared in
Ember.extend
do not show up there. I use such properties to set up default values (e.g.
[]
for array properties)

Answer

At the moment I solve it with the following snippet:

App.plainCopy = function (obj) {
  if (Ember.isArray(obj)) {
    return obj.map(App.plainCopy);
  } else if (typeof(obj) === "object") {
    if (App.Plainable.detect(obj)) {
      return obj.plainCopy();
    } else {
      throw new Error(Ember.String.fmt("%@ is not Plainable", [obj]));
    }
  } else {
    return obj;
  }
}

App.Plainable = Ember.Mixin.create({
  plainCopy: function() {
    var props = Ember.keys(this);
    var proto = this.constructor.prototype;
    for(p in proto) {
      if (proto.hasOwnProperty(p) && typeof(this[p])!=="function") {
        props.push(p);
      }
    }
    var copy = {};
    props.forEach(function(p) {
      copy[p] = App.plainCopy(this.get(p));
    }, this);
    return copy;
  }
});

It does not go up the class hierarchy and does not look into mixins (as I use for data objects which are quite simple form that point of view)