Languages
[Edit]
EN

JavaScript - deep compare of two objects with differences printing

10 points
Created by:
mkrieger1
726

In this article we are going to look how to make deep compare of two objects with differences printing in JavaScript.

Practical example

In this section extended equals() method logs difference between objects.

// ONLINE-RUNNER:browser;

function compare(a, b) {
    var logs = [];
    var log = function(log, path) {
        if (path) {
            logs.push(log + ' (path: ' + path + ').');
        } else {
            logs.push(log + '.');
        }
    };
    var analyse = function(a, b, path) {
        if (a === b) {
            return;
        }
        if (a instanceof Object && b instanceof Object) {
            if (a.constructor !== b.constructor) {
                log('Entities do not have same constructors', path);
                return;
            }
            for (const key in a) {
                if (a.hasOwnProperty(key)) {
                    if (!b.hasOwnProperty(key)) {
                        log('Property "' + key + '" does not exist in first entity', path + '.' + key);
                        continue;
                    }
                    analyse(a[key], b[key], path ? path + '.' + key : key) ;
                }
            }
            for (const key in b) {
                if (b.hasOwnProperty(key) && !a.hasOwnProperty(key)) {
                    log('Property "' + key + '" does not exist in second entity', path + '.' + key);
                }
            }
        } else {
            log('Entities are not equal', path);
        }
    };
    analyse(a, b, '');
    return logs;
}



// Usage example:

var object1 = {name: 'John', items: [1, 2, '3', {name: 'Item', z: [4]}]};
var object2 = {name: 'John', items: ['1', 2, 3, {name: 'Item 2', x: 3}]};

var logs = compare(object1,  object2);

if (logs.length == 0) {
    console.log('Objects are equal.');
} else {
    console.log('Objects are different in:');
    for (var  i = 0; i < logs.length; ++i) {
        console.log('  ' + logs[i]);
    }  
}

 

See also

  1. JavaScript - deep compare of two objects

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join