Last active
December 16, 2015 07:18
-
-
Save dustingetz/5397294 to your computer and use it in GitHub Desktop.
functional javascript - recursively walking a tree to build up a new one; could this be better factored as a reduce?
This file contains hidden or 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
| /** | |
| * recursively build a nested Backbone.Model or Backbone.Collection | |
| * from a deep JSON structure. | |
| * | |
| * undefined for regex values | |
| */ | |
| exports.modelify = function modelify (data) { | |
| if (_.isArray(data)) { | |
| return new Backbone.Collection(_.map(data, modelify)); | |
| } | |
| else if (_.isObject(data) && !_.isDate(data)) { | |
| var m = util.mapo(data, function(val, key) { | |
| return [key, modelify(val)]; | |
| }); | |
| return new Backbone.Model(m); | |
| } | |
| else { | |
| // data is a primitive or a date | |
| return data; | |
| } | |
| } | |
| var mapo = exports.mapo = _.compose(_.object, _.map); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment