Recursive/deep extend/assign in Underscore.js?

With Lodash (fork of underscore) you can.
Lodash’s _.extend method accept third (or higher) parameter to be a function, that receives values (old and new); So you can do something like this:

var deep = function(a, b) {
    return _.isObject(a) && _.isObject(b) ? _.extend(a, b, deep) : b;
};

var a = {a:{b:{c:1}}},
    b = {a:{b:{z:1}}};

_.extend(a,b,deep);

upd.
As Paolo Moretti said in comments, there is the same function in lodash called _.merge:

_.merge(a,b);

Leave a Comment