Skip to content

Instantly share code, notes, and snippets.

@dustingetz
Last active December 16, 2015 07:18
Show Gist options
  • Select an option

  • Save dustingetz/5397294 to your computer and use it in GitHub Desktop.

Select an option

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?
/**
* 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