Going through Ember.js documentation, I am not able to figure out how to create nested models. Assume that I have the following JSON:
App.jsonObject = {
I wrote my own simple model factory based on Alexandros K's solution but supporting ES6 modules. Thought I would share it :)
import Ember from 'ember';
var ModelFactory = Ember.Object.extend({});
ModelFactory.reopenClass({
getType(obj) {
if(!obj) {
return null;
}
if(Array === obj.constructor) {
return "array";
}
else if(typeof obj === "object") {
return "object";
}
return null;
},
// Factory method..
create: function (arg) {
const _this = this;
switch (this.getType(arg)) {
// Return an Ember Array
case "array":
var newArray = [];
arg.forEach(function(item) {
newArray.pushObject(_this.create(item));
});
return newArray;
// Or a recursive object.
case "object":
var newObject = Ember.Object.create();
for (var key in arg) {
if (arg.hasOwnProperty(key)) {
newObject.set(key, this.create(arg[key]));
}
}
return newObject;
default:
// Or just return the args.
return arg;
}
}
});
export default ModelFactory;
Usage:
ModelFactory.create(json)