public
Created

After some struggling, this is the pattern I came up with for mapping JSON data to nested custom classes.

  • Download Gist
gistfile1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
function Parent(data) {
 
// Let constructor work or without new.
// http://ejohn.org/blog/simple-class-instantiation/
// This makes it easier to use _.map below.
if (!(this instanceof Parent)) {
return new Parent(data);
}
 
// Use JSON data passed in, or set defaults values.
_.defaults(this, data, {
name: "",
children: []
});
 
// Map the children objects to the Child class.
this.children = _.map(this.children, Child);
}
 
function Child(data) {
if (!(this instanceof Child)) {
return new Child(data);
}
 
_.defaults(this, data {
name: ""
});
}
 
// Example JSON data.
var data = {
name: "foo",
children: [
{ name: "bar" },
{ name: "baz" }
]
};
 
// This will create a Parent object with an array of Child objects.
var parent = new Parent(data);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.