How can I get a list of the differences between two JavaScript object graphs?

前端 未结 10 559
终归单人心
终归单人心 2020-11-29 01:02

I want to be able to get a list of all differences between two JavaScript object graphs, with the property names and values where the deltas occur.

For what it is w

10条回答
  •  攒了一身酷
    2020-11-29 01:14

    None of the libraries I found were sufficient so I wrote my own AngularJS factory. It compares the objects in both ways and returns only the difference within the same structure.

    /**
     * Diff
     * Original author: Danny Coulombe
     * Creation date: 2016-05-18
     * 
     * Work with objects to find their differences.
     */
    controllers.factory('diff', [function() {
    
        var factory = {
    
            /**
             * Compare the original object with the modified one and return their differences.
             * 
             * @param original: Object
             * @param modified: Object
             * 
             * @return Object
             */
            getDifferences: function(original, modified) {
    
                var type = modified.constructor === Array ? [] : {};
                var result = angular.copy(type);
                var comparisons = [[original, modified, 1], [modified, original, 0]];
    
                comparisons.forEach(function(comparison) {
    
                    angular.forEach(comparison[0], function(value, key) {
    
                        if(result[key] === undefined) {
    
                            if(comparison[1][key] !== undefined && value !==    null && comparison[1][key] !== null && [Object, Array].indexOf(comparison[1][key].constructor) !== -1) {
    
                                result[key] = factory.getDifferences(value, comparison[1][key]);
                            }
                            else if(comparison[1][key] !== value) {
    
                                result[key] = comparison[comparison[2]][key];
                            }
    
                            if(angular.equals(type, result[key])
                            || result[key] === undefined
                            || (
                                comparison[0][key] !== undefined
                                && result[key] !== null
                                && comparison[0][key] !== null
                                && comparison[0][key].length === comparison[1][key].length
                                && result[key].length === 0
                            )) {
                                delete result[key];
                            }
                        }
                    });
                });
    
                return result;
            }
        };
    
        return factory;
    }]);
    

提交回复
热议问题