Skip to content

Instantly share code, notes, and snippets.

@nateroling
Created July 19, 2013 21:53
Show Gist options
  • Save nateroling/6042612 to your computer and use it in GitHub Desktop.
Save nateroling/6042612 to your computer and use it in GitHub Desktop.
After some struggling, this is the pattern I came up with for mapping JSON data to nested custom classes.
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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment