美文网首页
使用lodash深度对比出2个对象之间的差异

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

作者: TOPro | 来源:发表于2018-07-01 10:49 被阅读1647次

    原创在这里
    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个对象之间的差异

          本文链接:https://www.haomeiwen.com/subject/noscuftx.html