Recursive/deep extend/assign in Underscore.js?

后端 未结 6 1372
遥遥无期
遥遥无期 2020-11-29 10:47

Is there any way to get Underscore.js extend function:

Copy all of the properties in the source objects over to the destination object, and return t

6条回答
  •  猫巷女王i
    2020-11-29 11:28

    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);
    

提交回复
热议问题