Created
July 19, 2013 21:53
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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