Getting a diff of two json-objects

前端 未结 5 2028
执笔经年
执笔经年 2020-11-29 05:01

Scenario: I want a function that compares two JSON-objects, and returns a JSON-object with a list of the differences and if possible more data such as coverage metrics.

5条回答
  •  醉酒成梦
    2020-11-29 05:29

    contributing back my changes to Gabriel Gartz version. This one works in strict mode and removes the array check - will always be false. It also removes empty nodes from the diff.

    //http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object
    var isEmptyObject = function(obj) {
        var name;
        for (name in obj) {
            return false;
        }
        return true;
    };
    
    //http://stackoverflow.com/questions/8431651/getting-a-diff-of-two-json-objects
    var diff = function(obj1, obj2) {
        var result = {};
        var change;
        for (var key in obj1) {
            if (typeof obj2[key] == 'object' && typeof obj1[key] == 'object') {
                change = diff(obj1[key], obj2[key]);
                if (isEmptyObject(change) === false) {
                    result[key] = change;
                }
            }
            else if (obj2[key] != obj1[key]) {
                result[key] = obj2[key];
            }
        }
        return result;
    };
    

提交回复
热议问题