使用lodash深度对比/比较/对比出2个对象之间的差异

原创在这里
https://gist.github.com/Yimiprod/7ee176597fef230d1451

由于一些你知道的原因gist在国内经常无法访问,我搬运下源码

/**
 * Deep diff between two object, using lodash
 * @param  {Object} object Object compared
 * @param  {Object} base   Object to compare with
 * @return {Object}        Return a new object who represent the diff
 */
function difference(object, base) {
    function changes(object, base) {
        return _.transform(object, function(result, value, key) {
            if (!_.isEqual(value, base[key])) {
                result[key] = (_.isObject(value) && _.isObject(base[key])) ? changes(value, base[key]) : value;
            }
        });
    }
    return changes(object, base);
}

ex:

var a = {name:89757,date:{year:2017}}
var b = {name:89757,date:{year:2017,month:3}}

difference(a,b)
//{date:{month:3}}

你可能感兴趣的:(使用lodash深度对比/比较/对比出2个对象之间的差异)