EN
JavaScript - deep compare of two objects with differences printing
10 points
In this article we are going to look how to make deep compare of two objects with differences printing in JavaScript.
In this section extended equals()
method logs difference between objects.
xxxxxxxxxx
1
function compare(a, b) {
2
var logs = [];
3
var log = function(log, path) {
4
if (path) {
5
logs.push(log + ' (path: ' + path + ').');
6
} else {
7
logs.push(log + '.');
8
}
9
};
10
var analyse = function(a, b, path) {
11
if (a === b) {
12
return;
13
}
14
if (a instanceof Object && b instanceof Object) {
15
if (a.constructor !== b.constructor) {
16
log('Entities do not have same constructors', path);
17
return;
18
}
19
for (const key in a) {
20
if (a.hasOwnProperty(key)) {
21
if (!b.hasOwnProperty(key)) {
22
log('Property "' + key + '" does not exist in first entity', path + '.' + key);
23
continue;
24
}
25
analyse(a[key], b[key], path ? path + '.' + key : key) ;
26
}
27
}
28
for (const key in b) {
29
if (b.hasOwnProperty(key) && !a.hasOwnProperty(key)) {
30
log('Property "' + key + '" does not exist in second entity', path + '.' + key);
31
}
32
}
33
} else {
34
log('Entities are not equal', path);
35
}
36
};
37
analyse(a, b, '');
38
return logs;
39
}
40
41
42
43
// Usage example:
44
45
var object1 = {name: 'John', items: [1, 2, '3', {name: 'Item', z: [4]}]};
46
var object2 = {name: 'John', items: ['1', 2, 3, {name: 'Item 2', x: 3}]};
47
48
var logs = compare(object1, object2);
49
50
if (logs.length == 0) {
51
console.log('Objects are equal.');
52
} else {
53
console.log('Objects are different in:');
54
for (var i = 0; i < logs.length; ++i) {
55
console.log(' ' + logs[i]);
56
}
57
}